I needed to wrap all the images in the text in a div tag, after removing paragraphs, if any. I found a similar example of a regular expression for another tag, changed it to fit my task. Everything works, but I would like to figure out how. In the help on regular expressions, I could not find the role of the ~ sign anywhere, but if you remove it, the code stops working. Tell me, please, what this sign means and how to use it properly.

 $search = array( '(<p[^>]*?>(<img[^>]*?>)</p>)', '~(<img[^>]*?>)~' ); $replace = array( '$1', '<div>$1</div>' ); $result = preg_replace($search, $replace, $text); 

    1 answer 1

    The ~ characters represent the beginning and end of a regular expression. These characters can be replaced, for example with # or / . Usually choose characters that are not used to describe the regular expression itself.

    In the official documentation, these characters are called delimiters .

    • The 1st and last characters must be the same. I don’t know if pair brackets can be used in PHP - andy.37
    • @ andy.37, the documentation says you can : You can also use a delimiter in the form of brackets, where the starting and ending delimiters are respectively opening and closing brackets. (), {}, [] and <> are valid pairs of delimiters. - Grundy
    • /(.*)/isu After the separator, there may be modifiers. In this case, the first and last characters are different. - ilyaplot
    • @ilyaplot, you are right. I meant that the characters separator d. same or be paired brackets: {(.*)}isu . - andy.37
    • Thank. And tell me more, why does everything work in the first case without these characters? Where '(<p[^>]*?>(<img[^>]*?>)</p>)' - Anna Kuimova