I remove the first occurrence of a html tag in a string with preg_replace
as
$html = preg_replace('#<p>(.*?)</p>#i', '', $html, 1);
How can I save the deleted substring as a new string:
$deleted = '<p>...</p>';
I remove the first occurrence of a html tag in a string with preg_replace
as
$html = preg_replace('#<p>(.*?)</p>#i', '', $html, 1);
How can I save the deleted substring as a new string:
$deleted = '<p>...</p>';
How about using preg_replace_callback
which passes the match to a user defined function.
$str = preg_replace_callback($re, function ($m) use (&$p) { $p = $m[0]; }, $str, 1);
$m
any variable name for the matches array where index 0
is the full pattern matchuse
(&$p)
any variable name for storing the match (passed by reference).to get the substring you can use preg_match():
preg_match('#<p>(.*?)</p>#i', $html, $matches);
just check the $matches variable it contain what you need.
If matches is provided, then it is filled with the results of search. $matches[0] will contain the text that matched the full pattern, $matches1 will have the text that matched the first captured parenthesized subpattern, and so on.
after that use preg_replace
to delete the <p>
tag.
but if you want only to remove the <p>
tag and keep the substring just preg_replace
like this :
$html = "left <p>substring</p> right";
$html = preg_replace('#</?p>#i', '', $html);
echo $html;
output :
left substring right
try using :
$result = preg_match('#<p>(.*?)</p>#i', $html);