php regular expression tester,“preg_match():編譯失敗:PHP中沒有匹配的括號”。

Wondering if anyone out there can shed some light on why the following regular expression is failing when used in PHP's preg_match function:-

想知道是否有人能解釋為什么在PHP的preg_match函數中使用下列正則表達式時失敗:-

$str = '\tmp\phpDC1C.tmp';

preg_match('|\\tmp\\([A-Za-z0-9]+)|', $str, $matches);

print_r($matches);

?>

This results in the error message "preg_match(): Compilation failed: unmatched parentheses" despite the fact that the pattern appears to be valid. I've tested it with an online PHP Regular Expression tester and the Linux tool Kiki. Seems like PHP is escaping the opening parenthesis rather than the backslash.

這導致了錯誤消息“preg_match():編譯失敗:不匹配的括號”,盡管模式看起來是有效的。我已經用一個在線PHP正則表達式測試器和Linux工具Kiki對它進行了測試。看起來PHP是轉義開括號而不是反斜杠。

I've got round the issue by using str_replace to swap the backslashes for forward ones. This works for my situation but it would be nice to know why this regular expression is failing.

通過使用str_replace將反斜杠替換為向前斜杠,我解決了這個問題。這適用於我的情況,但是如果知道這個正則表達式為什么會失敗,那就太好了。

4 个解决方案

#1

16

To encode a literal backslash, you need to escape it twice: Once for the string, and once for the regex engine:

要對字面反斜杠進行編碼,需要轉義兩次:一次用於字符串,一次用於regex引擎:

preg_match('|\\\\tmp\\\\([A-Za-z0-9]+)|', $str, $matches);

In PHP (when using single-quoted strings), this is only relevant for actual backslashes; other regex escapes are OK with a single backslash:

在PHP中(使用單引號字符串時),這只與實際的反斜杠有關;其他的regex轉義可以使用一個反斜杠:

preg_match('/\bhello\b/', $subject)

This is covered in the manual (see the box labeled "Note:" at the top of the page).

這在手冊中有介紹(請參閱在頁面頂部標有“注意:”的方框)。

#2

1

you have to use |\\\tmp\\\([A-Za-z0-9]+)| expression

你必須使用| \ \ \ tmp \ \ \([A-Za-z0-9]+)|表達式

but there are better way to get file name because of concrete form of string. for example:

但是由於字符串的具體形式,有更好的方法來獲取文件名。例如:

substr($str, 5, -4);

think about memory usage

考慮內存使用

#3

0

strange I just tested using the same online regex tester which you mentioned and it compiled without error :

奇怪的是,我剛剛用你提到的那個在線regex測試器進行了測試,結果沒有出錯:

$ptn = "/

preg_match('|\\tmp\\([A-Za-z0-9]+)|', $str, $matches); print_r($matches); ?>;/";

$str = "";

preg_match($ptn, $str, $matches);

print_r($matches);

?>

#4

0

Use the next regex:

使用下一個正則表達式:

php >$str = '\tmp\phpDC1C.tmp';

php >preg_match('/[\\\\]tmp[\\\\]([A-Za-z0-9]+)/', $str, $matches);

php >print_r($matches);

Array

(

[0] => \tmp\phpDC1C

[1] => phpDC1C

)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值