2010-09-27 5 views
1

J'ai essayé de faire fonctionner cette regex. Supposons que pour analyser une URL, si la chaîne '_skipThis' est trouvée, ne correspond pas à la chaîne. Des backreferences sont également nécessaires. Par exemple:PHP Preg_match: essaie de faire correspondre une chaîne où une sous-chaîne n'existe pas dans la chaîne

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. 

J'ai essayé la regex suivante ..

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

S'il vous plaît aidez-moi! Merci d'avance!!!

Répondre

0

Juste correspondre _skipThis et retourner false s'il est trouvé.

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

(Bien sûr, il est une expression régulière pour cela. En supposant _skipThis n'apparaît avant la première /,

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

Sinon, si le _skipThis apparaît besoin n'importe où à éviter,

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

Essayez ceci:

$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"; 

Sortie:

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

Merci beaucoup pour votre aide. Il est nécessaire que la «partie_particulière de la chaîne» soit différente tout le temps. Merci! –

Questions connexes