-1

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>';
Googlebot
  • 15,159
  • 44
  • 133
  • 229

3 Answers3

1

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 match
  • use (&$p) any variable name for storing the match (passed by reference).

See this demo at eval.in

bobble bubble
  • 16,888
  • 3
  • 27
  • 46
0

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
yoeunes
  • 2,927
  • 2
  • 15
  • 26
0

try using :

$result = preg_match('#<p>(.*?)</p>#i', $html);
Mourani
  • 60
  • 2
  • 1
    What question are you answering? `preg_match` returns a boolean, what are you doing after? – Toto Aug 06 '17 at 10:25