PHP get the line between the tag [Multiple tags in one line]

I searched a lot, but I can not find anything similar to my problem. I found the link, but I don’t think they really answered the question.

Say I have this line

$my_string = "I am with a [id]123[/id] and [id]456[id]"; 

I want to get the whole number between [id] [/ id]. I only have this function to get a string between.

 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 = 'I am with a [id]123[/id] and [id]456[id]'; $parsed = get_string_between($fullstring, '[id]', '[/id]'); 

But this function only returns the first line found in $ fullstring. Maybe I can get 123,456 or an array of array ('123', '456'). I am really stuck with this.

+4
php tags
03 Feb '16 at 4:21
source share
1 answer

You can simply use the preg_match_all function for PHP along with the following regular expression

 ~\[id\](.*?)\[\/id\]~ 

as

 $my_string = "I am with a [id]123[/id] and [id]456[/id]"; preg_match_all("~\[id\](.*?)\[\/id\]~",$my_string,$m); print_r($m[1]); 
+6
Feb 03 '16 at 4:38
source share



All Articles