Home > Back-end >  How to get text is not between html tags and text is between html
How to get text is not between html tags and text is between html

Time:11-13

I have an issue i have this html:

<strong>this test is strong</strong> this text is out tags

I would like to get something like this: $var1 = this test is strong $var2 = this text is out tags

I tried this:

preg_match('/<strong>(.*?)<\/strong>/s', $toolTipText, $var);

and that return

$var[0] = this test is strong

but i also need to get this text is out tags

Could you please help me?

CodePudding user response:

You can extend the regex with another capturing group to capture anything after the closing </strong> tag.

This would show up in $var[2] because it is the 2nd capturing group () in your regex:

preg_match('/<strong>(.*?)<\/strong>(.*)/s', $toolTipText, $var);

//$var[1] = "<strong>this test is strong</strong>"
//$var[2] = " this text is out tags"

CodePudding user response:

You can use preg_split using your regex (or with \s* added on both ends to trim the items from whitespace) with PREG_SPLIT_DELIM_CAPTURE option:

print_r(preg_split('/\s*<strong>(.*?)<\/strong>\s*/s', $text, -1, PREG_SPLIT_NO_EMPTY | PREG_SPLIT_DELIM_CAPTURE));

See the PHP demo.

Some more details from the docs:

PREG_SPLIT_NO_EMPTY
If this flag is set, only non-empty pieces will be returned by preg_split().

PREG_SPLIT_DELIM_CAPTURE
If this flag is set, parenthesized expression in the delimiter pattern will be captured and returned as well.

  • Related