2010-09-27 135 views
1

我一直在試圖獲得這個正則表達式的工作。假設解析URL,如果找到字符串'_skipThis',則不匹配字符串。反向引用也是需要的。例如:PHP Preg_match:嘗試匹配字符串中不存在子串的字符串

String 1: a_particular_part_of_string/a/b/c/d/e/f 
Result: preg_match should return true 
Backreference: $1 -> a_particular_part_of_string, $2 -> /a/b/c/d/e/f 

String 2: a_particular_part_of_string_skipThis/a/b/c/d/e/f 
Result: preg_match should return false. 
Backreference: nothing here. 

我曾嘗試以下的正則表達式..

reg1 = ([a-zA-Z0-9_]+)(\/.*) 
reg2 = ([a-zA-Z0-9]+(?!_skipThis))(\/.*) 
reg3 = ((?!_skipThis).*)(\/.*) 
reg4 = ((?!_skipThis)[a-zA-Z0-9_]+)(\/.*) 

請幫幫我!提前致謝!!!

回答

0

只匹配_skipThis並返回如果找到。

if (strpos($theString, '_skipThis') === false) { 
     // perform preg_match 
} else 
     return false; 

(當然有這個正則表達式。假設_skipThis第一/之前纔出現,

return preg_match('|^([^/]+)(?<!_skipThis)(/.*)$|', $theString); 
//     -------    ----- 
//      $1 -------------- $2 
//       Make sure it is *not* preceded '_skipThis' 

否則,如果_skipThis出現的任何地方需要避免,

return preg_match('|^(?!.*_skipThis)([^/]+)(/.*)$|', $theString); 
//     --------------- 
//     Make sure '_skipThis' is not found anywhere. 
0

試試這個:

$str1 = 'a_particular_part_of_string/a/b/c/d/e/f'; //1 
$str2 = 'a_particular_part_of_string_skipThis/a/b/c/d/e/f'; //0 
$keep = 'a_particular_part_of_string'; 
$skip = '_skipThis'; 

$m = array(); 
if(preg_match("/($keep)(?!$skip)(.*)$/", $str1, $m)) 
    var_dump($m); 
else 
    echo "Not found\n"; 

$m = array(); 
if(preg_match("/($keep)(?!$skip)(.*)$/", $str2, $m)) 
    var_dump($m); 
else 
    echo "Not found\n"; 

輸出:

array(3) { 
    [0]=> 
    string(39) "a_particular_part_of_string/a/b/c/d/e/f" 
    [1]=> 
    string(27) "a_particular_part_of_string" 
    [2]=> 
    string(12) "https://stackoverflow.com/a/b/c/d/e/f" 
} 

Not found 
+0

非常感謝你的幫助。 「a_particular_part_of_string」的含義是不一樣的。謝謝! – 2010-09-27 16:18:28