user3548161 user3548161 - 7 months ago 38
PHP Question

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;

Answer

So if based on comments foo is a line delimiter and the string is essentially to be treated as an associate array of key => values

<?php
    $string = 'foo name stoner loller bar php haystack needle fruit apples foo name roddy koala bar php haystack needle fruit guavas';

    //Get all of the arrays we will need to search
    $hayStacks = explode("foo", $string);

    foreach($hayStacks as $hayStack){
        $words = explode(' ', $hayStack);
        //Enter the key you want to find and then get the next element value.
        echo $words[array_search("name", $words)+1]."<br>";
        echo $words[array_search("fruit", $words)+1]."<br>";
    }
?>