Ben
Ben

Reputation: 59

Use regex in PHP to remove all the occurances of html <a> tag

I have following PHP code:

$originalStr = '<p>start<a class="wt_article_link" onmouseover="WeiboCard.show(2789895193, \'sports\' , this)" href="http://weibo.com/u/2789895193?zw=sports" target="_blank">[x]</a> middle <a class="wt_article_link" onmouseover="WeiboCard.show(2094902981, \'sports\' , this)" href="http://weibo.com/u/2094902981?zw=sports" target="_blank">[微博]</a> end</p>';

$pattern = '~<a(.*)>(.*)</a>~';
$newStr = preg_replace($pattern, '', $originalStr);
echo $newStr;

Expected result:

<b><p>start middle end</p></b>

Actual result:

<b><p>start end</p></b>

Could anyone help me write the correct regex to achieve expected result? Thanks.

Upvotes: 1

Views: 72

Answers (1)

bwoebi
bwoebi

Reputation: 23787

Change your regex to be ungreedy: add the U modifier.

$pattern = '~<a(.*)>(.*)</a>~U';

Should work for your needs.

Upvotes: 1

Related Questions