Reputation: 2110
I need to add a string (in this case is a div
) after an img tag on each post on wordpress. I know where do it but I don't know how. I tried with preg_replace
but it doesn't work:
$content = preg_replace('/<img[^>]+\>/i', '/<img[^>]+\>/i <div...>', $content);
As result i get /<img[^>]+\>/i <div...>
and not the img followed by .
How can I do?
Upvotes: 2
Views: 698
Reputation: 173572
The second argument to preg_replace()
should be the replacement string, not another regular expression. You can use $0
(the whole match) or $1 ~ $9
for each of the memory captures you have. In your case you don't have any memory captures (stuff between parentheses), so:
$content = preg_replace('/<img[^>]+>/i', '$0 <div...>', $content);
Btw, you don't have to escape the >
in the expression.
Upvotes: 1
Reputation: 12322
The replace part should be: '$0 <div...>'
, which basically sais: take what you have found with my pattern and append my div.
So your code should like:
$content = preg_replace('/<img[^>]+\>/i', '$0 <div...>', $content);
Upvotes: 2
Reputation: 7784
$content = "<img /> <br/> <img />" ;
$content = preg_replace('/(<img[^>]+\>)/i', '$1 <div></div>', $content);
echo htmlentities($content) ;
Upvotes: 0