Ivan Topić Ivan Topić - 1 year ago 65
PHP Question

Replace all ocurrence of something with only one

How to replace all ocurrences of

<p>[gallery ids=""]</p>
if they exist with only one?

$string = "/\<p\>\[gallery ids=\"\"\]\<\/p\>/";
$content = "asdfsdfdsafasdfaasfddsaf <p>[gallery ids=""]</p><p>[gallery ids=""]</p><p>[gallery ids=""]</p>";
if (preg_match_all($string, $content, $matches)) {


should be
asdfsdfdsafasdfaasfddsaf <p>[gallery ids=""]</p>

Answer Source

Simple solution using preg_replace function:

$content = 'asdfsdfdsafasdfaasfddsaf <p>[gallery ids=""]</p><p>[gallery ids=""]</p><p>[gallery ids=""]</p>';
$content = preg_replace("/(<p>\[gallery ids=\"\"\]<\/p>){2,}/", "$1", $content);

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download