简体   繁体   中英

PHP Regex: match character set OR end of string

I am porting code from Nodejs to PHP and keep getting errors with this regular expression:

^/[a-z0-9]{6}([^0-9a-z]|$)

PHP complains about dollar sign:

Unknown modifier '$'

In javascript I was able to check if a string is ending with [^0-9a-z] or END OF STRING How do I do this in PHP with preg_match ?

My PHP code looks like this:

<?
$sExpression = '^/[a-z0-9]{6}([^0-9a-z]|$)';
if (preg_match('|' . $sExpression .  '|', $sUrl)) { ... }
?>

The JS code was similar to this:

var sExpression = '^/[a-z0-9]{6}([^0-9a-z]|$)';
var oRegex      = new RegExp(sExpression);
if (oRegex.test(sUrl)) { ... }

Thanks in advance.

To match a string that starts with a slash, followed by 6 alphanumerics and is then followed by either the end-of-string or something that's not alphanumeric:

preg_match('~^/[a-z0-9]{6}([^0-9a-z]|$)~i', $str);

The original JavaScript probably used new RegExp(<expression>) , but PCRE requires a proper enclosure of the expression; those are the ~ characters I've put in the above code. Btw, I've made the expression case insensitive by using the i modifier; feel free to remove it if not desired.

Update

You were using | as the enclosure; as such, you should have escaped the pipe character inside the expression, but by doing so you would have changed the meaning. It's generally best to choose delimiters that do not have a special meaning in an expression; it also helps to choose delimiters that don't occur as such in the expression, eg my choice of ~ avoids having to escape any character.

Expressions in PCRE can be generalised as:

<start-delimiter> stuff <end-delimiter> modifiers

Typically the starting delimiter is the same as the ending delimiter, except for cases such as [expression]i or {expression}i whereby the opening brace is matched with the closing brace :)

Could you fix the regx first?

^/[a-z0-9]{6}([^0-9a-z]|$) 

try this

UPDATE: as others pointed out I'm and idot and saw a / as a \\ .. lol

Ok well go at this again,

Id avoid using the "|" and just do it this way.

if (preg_match('/^\/[a-z0-9]{6}([^0-9a-z]|$)/', $sUrl)) { ... }

reducing this to just matching a particular character or end of string (php)

\D777(\D|$)\

this will match

xxx777xxx or xxx777 but not xxx7777 or xxx7777xxx

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