PHP preg_replace making regex optional?

I have content that I am trying to parse ...

I have html and with html I want to replace all my img tags with a custom string. Now one of the problems that I am facing is that there is some content that comes in: image tags are between the anchor.

ex.

<a href="link"><img></a>

In the following code, I have work ... but I want it to be optional, so if no anchor tag is surrounded by the img tag, does anyone have a good regex resource or can it help me?

Thank!

$content = preg_replace('#<a.*?>'.$image_tag.'</a>#i', "{$image_id}", $content);
+3
source share
2 answers
  • The question icon after the token makes this token optional.
  • (?...) ( ).
  • , (?...)? .

, :

$content = preg_replace('#(?:<a.*?>)?'.$image_tag.'(?:</a>)?#i',
                        "{$image_id}",
                        $content);

, , , HTML.

+4

-

$content = preg_replace('#'.$image_tag.'#i', "{$image_id}", $content);

? ^ $ , $image_tag , <a> . , :

$content = preg_replace('#(<a.*?>)?'.$image_tag.'(</a>)?#i', "{$image_id}", $content);

<a> </a> , ? (.. 0 1 )

+2

Source: https://habr.com/ru/post/1764606/


All Articles