I've very odd task to do.
I need to grab text from html tags using preg_match() function in PHP. Problem is that text I need is between closing and opening html tags or this text with tags.
Below is my html string:
<h2>Title of post</h2> 1 category <strong>task 1</strong> 1 category <strong>task 2</strong> 1 category <strong>task 3</strong>
To be more specific: I need string " 1 category " between </h2>
and <strong>
tag.
When i try to grab text between opening and closing tags - It's working fine and I'm using this function:
preg_match_all('#<strong>(.*?)</strong>#',$string,$matches);
I've tried many combinations to get text between closing and opening tags. None of them worked out. I've ended using function like this:
preg_match_all('#<\/strong>(.*?)<strong>#',$content,$matches_all);
With no results.
The strange thins is that on online regex testers this function with above pattern with above function works sometimes.
Do I have bad pattern? Am I missing some flags? Do you know what can be best way to get text in this way? Unfortunately I have to do with Regex approach, the solutions like XMLDomParser is not allowed in my case.
Thanks a lot for help.
Looks like something wrong with your php installation/configuration.
Your code as it's.
$content = '<h2>Title of post</h2> 1 category <strong>task 1</strong> 1 category <strong>task 2</strong> 1 category <strong>task 3</strong> ';
preg_match_all('#<\/h2>(.*?)<strong>#',$content,$matches);
print_r($matches);
Output:
Array
(
[0] => Array
(
[0] => </h2> 1 category <strong>
)
[1] => Array
(
[0] => 1 category
)
)
Live demo
Note: Since there is only one match of your pattern ( between </h2>
<strong>
) you can access like $maches[1][0]
or use preg_match
.
If you want all pieces of text between a closing and opening tag, you could use this code. Note that I changed your text so that the text between each set of closing/opening tags was different so that it was more obvious that the match was finding each value.
$str = '<h2>Title of post</h2> 1 category <strong>task 1</strong> 2 category <strong>task 2</strong> 3 category <strong>task 3</strong> ';
preg_match_all('#(?:</[^>]+>)(.*?)<#', $str, $matches);
print_r($matches[1]);
Output:
Array
(
[0] => 1 category
[1] => 2 category
[2] => 3 category
)