简体   繁体   中英

Regex pattern matching incorrectly

I have a regex pattern that is trying to match a string, but it's doing it incorrectly so I'm going to point out parts of the regex pattern and what it does in hopes of getting it right this time:

~  : the start of the regex pattern
,  : trying to match the , at the start of the string
.* : 0 or more of any characters in between
=? : stop at the first match of the rest of the pattern
\. : a period
\" : a quote
/  : a slash
>  : arrow right
<  : arrow left
~  : end of pattern

$content = ", not good in any manner or degree. See more.\"/><"

$regex = "~,.*=?\.\"/><~"; 
preg_match_all("/$regex/siU", $content, $matches);

echo "<pre>";
print_r($matches);
echo "</pre>";

Unknown modifier '/'
Unknown modifier '>'
Unknown modifier '<'

But as far as I know only these [\\^$.|?*+(){} are regex meta characters that needs to be escaped. Anyway, I escaped the / and the <, and the error went away but this time I got an empty array instead.

$regex = "~,.*=?\.\"\/\>\<~"; 
preg_match_all("/$regex/siU", $content, $matches);

echo "<pre>";
print_r($matches);
echo "</pre>";

Array
(
    [0] => Array
        (
        )
)

Can anyone tell me what I'm doing wrong?

You have to escape all your backslashes and also you are using two delimiters ~ and / , you can use below code:

$regex = "~,.*=?\\.\"/><~siU"; 
preg_match_all("$regex", $content, $matches);

You can quickly see this using any regex online tool like regex101

https://regex101.com/r/dT1pQ7/1

Btw, not sure if you wanted to make your = optional or not but =? makes = to be optional.

Update: after reading your comment to "stop" at the first match you have to use a non greedy operator by adding ? after the quantifier as Chris said makes the trick, so .+? or .*? are lazy or nongreedy quantifiers making to stop at the first occurrence

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM