Search code examples
phpsubstrsubstring

PHP substr loop output


How to loop through $string text to get all instances at the moment my code only out puts first line : fruit apple name stone

How do i make it also check the second line and output :fruit guava name roddy

for example in the $string text below we have :
foo name stoner and foo name roddy At the moment i can only extract name stoner and script stops. I would also like it to extract name roddy.

sorry if i dont make sense. my english is not that good

$string = 'foo name stoner loller bar php haystack needle fruit apples
foo name roddy koala bar php haystack needle fruit guavas';
$needle = 'fruit';
$needle1 = 'name';
$str = substr($string, strpos($string, $needle) + strlen($needle), 6);
$str1 = substr($string, strpos($string, $needle1) + strlen($needle1), 6);
echo  $needle. $str; 
echo " ";
echo  $needle1. $str1;

Solution

  • Have a look at this regex, is this what you want?

     $string = 'foo name stoner loller bar php haystack needle fruit apples
    foo name roddy koala bar php haystack needle fruit guavas';
    preg_match("/(name \w{6}).*(fruit \w{6})/", $string, $output);
    

    output:

    array(3
      0 =>  name stoner loller bar php haystack needle fruit apples
      1 =>  name stoner
      2 =>  fruit apples
    )
    array(3
      0 =>  name roddy koala bar php haystack needle fruit guavas
      1 =>  name roddy
      2 =>  fruit guavas
     )
    

    http://www.phpliveregex.com/p/fzF

    Edited to only match 6 characters, but this means "roddy" line is not matched as it's 5 chars only.