Ivan Topić Ivan Topić - 3 months ago 9
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)) {

}


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

Answer

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);

print_r($content);
Comments