Ivan Topić
Ivan Topić

Reputation: 3185

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>

Upvotes: 1

Views: 51

Answers (2)

NDM
NDM

Reputation: 6830

You are escaping way to many things, you need to find the matter with a quantifier, {1,}in this case: between 1 and unlimited times.

Also add a g global modifier in case you've got newlines in your content.

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

Upvotes: 1

RomanPerekhrest
RomanPerekhrest

Reputation: 92854

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

Upvotes: 2

Related Questions