Page 1 of 1

Get values in between tags

Posted: Wed Dec 17, 2008 6:49 am
by zerandib
How to get the values in between <abcd> tage


$v = "this is test <abcd>value1 ok</abcd> dont know tell me <abcd>value33 kooo ok</abcd> this is php regress <abcd>teeth value</abcd> ok how";

Output needs to be like this;
value1 ok
value33 kooo ok
teeth value


When i write this code, it show only the first value. (i.e: value1 ok)
How to get the other 2 values!

Code: Select all

<?php
 
function get_string_between($string, $start, $end){
        $string = " ".$string;
        $ini = strpos($string,$start);
        if ($ini == 0) return "";
        $ini += strlen($start);   
        $len = strpos($string,$end,$ini) - $ini;
        return substr($string,$ini,$len);
}
 
$fullstring = "this is test <abcd>value1 ok</abcd> dont know tell me <abcd>value33 kooo ok</abcd> this is php regress <abcd>teeth value</abcd> ok how";
$parsed = get_string_between($fullstring, "<abcd>", "</abcd>");
 
echo $parsed; 
?>

How to get the other values that is in between <abcd>

Thanks

Re: Get values in between tags

Posted: Wed Dec 17, 2008 10:36 am
by toasty2
Try treating it as XML. Just load the string into a simplexml object, access the element(s).

Code: Select all

 
$xml = simplexml_load_string($v);
foreach($xml->abcd as $x)
{
     echo $x;
}
 

Re: Get values in between tags

Posted: Wed Dec 17, 2008 9:37 pm
by ryanday
<([A-Z][A-Z0-9]*)\b[^>]*>(.*?)</\1>

Will grab the values in between tags. This is ripped from http://www.regular-expressions.info/examples.html

I'm not very good with regex, but that site has given me help solving problems like the one you have posted.