Hello friends I am just learning php i want to ask you something, how can i check position no of particular word(Not single character) in string example $str = "web design hosting website hosting domain free hosting"; what if i want to find posting no of all three "hosting" in above example it must result position no 3, 5 and 8 if you have idea tell me
$str = "web design hosting website hosting domain free hosting"; $wanted = 'hosting'; $words = explode(' ',$str); $ticker = 0; foreach ($words as $value){ $ticker ++; if ($value == $wanted){ echo 'result '.$ticker.' matches the wanted word'."\n"; } } Code (markup):
This will not work because what if i want chck positing of Something like "web design" (space between two words) .
Ok, for two words try: $str = "web design hosting website hosting domain free hosting"; $wanted = 'webdesign'; $str = str_replace(array('web design', 'webdesign'), array('webdesign', 'somethingElseNotWhatWeWant'), $str); $words = explode(' ',$str); $ticker = 0; foreach ($words as $value){ $ticker ++; if ($value == $wanted){ $ticker ++; // Remove this line if you want to count a two word wanted string as one word echo 'result '.$ticker.' matches the wanted word'."\n"; } } Code (markup):
Thanks for your Quick reply and mindbowing 'mind, i near from my solution just one problem in above example "web design" is a variable it might be also like "website design" and "domain hosting" etc, any way thanks for vary quick reply
Yep that can be achieved by putting the wanted words in an array then using the in_array() function like the following: $str = 'web design hosting website hosting domain free hosting third term'; $wanted = array('websitedesign', 'domainhosting', 'thirdterm'); $str = str_replace(array('website design', 'websitedesign', 'domain hosting', 'domainhosting', 'third term', 'thirdterm'), array('websitedesign', 'somethingElseNotWhatWeWant', 'domainhosting', 'somethingElseNotWhatWeWant', 'thirdterm', 'somethingElseNotWhatWeWant'), $str); $words = explode(' ',$str); $ticker = 0; foreach ($words as $value){ $ticker ++; if (in_array($value, $wanted)){ $ticker ++; // Remove this line if you want to count a two word wanted string as one word echo 'result '.$ticker.' matches the wanted word'."\n"; } } Code (markup):
Too complex, here is a simple version $str = "web design hosting website hosting domain free hosting"; $x = explode(" ", $str); for ($i = 0; $i < count($x); $i++) { if (strpos($x[$i], "hosting")) $found[] = $i + 1; } print_r($found); PHP: Edit: My bad, didn't read u want multiple words.