Hi all,

This code works, but I have a feeling I have done it a long winded/problematic way since my knowledge of regex isn't what it could be, anyone able to comment?

What I am trying to do is obtain the 3 items seperated by '-' inbetween the 2 local tags from the string which could possible have varying amounts of text around it.

Thanks in advance
Stelf

$strtemp = "random text [local]1-200-1[/local] more text";

if (eregi("\[local\]", $strtemp)) {
	$result = preg_split('(\[local\]|\[/local\])', substr(stristr($strtemp, '[local]'), 6), -1);
	$result = explode("-", $result[0]);
	print_r($result);
}

Results which is correct:-

Array
(
    [0] => 1
    [1] => 200
    [2] => 1
)

    Hi,

    try the following:

    <?PHP
    
    $theString="blu blab [local]12-45-13[/local]ds fd[local]1-4-5[/local]3";
    
    if ($cnt = preg_match_all("/\\[local\\](\\d+)-(\\d+)-(\\d+)\\[\\/local\\]/i",$theString,$theArray,PREG_SET_ORDER)) {
       for($i=0;$i<$cnt;$i++) {
          for ($j=1;$j<=3;$j++)
             echo $theArray[$i][$j]." - ";
    
      echo "<br>\n";
       }
    }
    ?>
    

    with using preg_match_all php tries to do a subsequent match. This will return all matches if your string contains the tags more than once.

    $theArray is an array of arrays that contain the parenthesized subpattern.

    $theArray[$i][0] contains the first number $theArray[$i][1] the second and so on.

    $i is the first, second .... match.

    Best of all preg_match_all already returns an array like you want it. preg_match_all returns 0 if it wasn't able to match anything.

    This is a one line solution 🙂

      Thanks Tsinka, working great for me 🆒

        Write a Reply...