Jump to content

Problem searching in a string


Perfidus

Recommended Posts

I have developed this function starting from another I found in PHP manual, it should find substrings between all the pairs of given substrings

 

function extractBetweenDelimeters($inputstr,$delimeterLeft,$delimeterRight) { 
   $number=substr_count($inputstr, $delimeterLeft); 
   $adding=0; 
   for ($k = 0; $k < $number; $k++) { 
   $posLeft  = stripos($inputstr,$delimeterLeft,$adding)+strlen($delimeterLeft); 
   $posRight = stripos($inputstr,$delimeterRight,$adding); 
   $values=array(); 
   $values[]= substr($inputstr,$posLeft,$posRight-$posLeft); 
   $adding=$adding+$posRight+strlen($delimeterRight); 

} 
return $values; 
} 

 

I'm using the function with a string in which there are two coincidences, but I only get the first one...

Can't see why it is ignoring the second one!!

 

Link to comment
https://forums.phpfreaks.com/topic/91140-problem-searching-in-a-string/
Share on other sites

try

<?php
function extractBetweenDelimeters($str,$delimeterLeft,$delimeterRight) { 
    $k = strlen($str);
    $values = array();
    $pos = $pos1 = 0;
    while (1)
    {
        $pos = strpos($str, $delimeterLeft, $pos1);
        if ($pos !== false){
           $pos1 = strpos($str, $delimeterRight, $pos);
           $values[] = substr($str, $pos+1, $pos1-$pos-1); 
        }
        else break;
        $pos = $pos1;
    }
    return $values;
} 

$str = "Lorem <ipsum> sit dolor <consecutor> amet";
$val = extractBetweenDelimeters($str,'<','>');
echo '<pre>', print_r($val, true), '</pre>';
?>

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.