php正則表達式問題
問題:
Warning: preg_match(): Unknown modifier ‘/‘ in D:\wwwroot\www.xb.com\t.php on line 6
bool(false) NULL
我的代碼:
<?php
$str = ‘‘;
$isMatched = preg_match("/http://www.chinanews.com/gn/2018/07-04/8555660.shtml/", $str, $matches);
var_dump($isMatched, $matches);
問題原因:
上述正則的定界符是斜杠’/’, 所以以此往後找,再找一個斜杠’/’,就結束了,得到的是:
/http:/
所以,後面跟著的內容:
/www.chinanews.com/gn/2018/07-04/8555660.shtml/
就沒法識別了。
解決辦法是:
1. 把定界符,改為別的,和當前正則表達式中的字符,不會沖突的,比如:
"#/http://www.chinanews.com/gn/2018/07-04/8555660.shtml#";
就可以了。
2. 在定界符內的‘/‘前面加上轉義字符‘\‘, 如下
"/http:\/\/www.chinanews.com\/gn\/2018\/07-04\/8555660.shtml/"
<?php
$str = ‘‘;
//方法一:
$isMatched = preg_match("#http://www.chinanews.com/gn/2018/07-04/8555660.shtml#", $str, $matches);
//方法二:
// $isMatched = preg_match("/http:\/\/www.chinanews.com\/gn\/2018\/07-04\/8555660.shtml/", $str, $matches);
var_dump($isMatched, $matches);
php正則表達式問題