2016-09-12 7 views
1

Ich versuche, ein regualr Ausdruck zu schreiben ungültige URL-Musterprüfen url slash Zählmuster

ich folgendes Muster passen wollen entsprechen:

/article/test-string/ 

Oben ist eine ungültige URL, aber folgende gelten

/article/abc/test-string/ and /article/xyz/abc/test-string/ 

Ich möchte diejenigen, die nur einen Wert nach Artikel Schrägstrich haben übereinstimmen. Bitte helfen Sie, ich versuche folgendes verwenden, aber es ist passend zu allen:

/article/(.*)/$ 

Antwort

2

.* Matches 0 oder mehr von jedem Charakter, so wird /article/(.*)/$ alle URIs übereinstimmen, die /article/ in ihm.

Sie diese Regex verwenden können nur nur eine nicht-slash-Komponente nach /article/ zu überprüfen:

$re = '~^/article/[^/]*/$~'; 
  • [^/]* # passt 0 oder mehr von beliebigen Zeichen, das nicht /
  • /$ # ist Spiele / am Ende
  • ~ wird als Regex-Begrenzer verwendet, um zu vermeiden, /
+1

danke Anubhava Ji, ist es für mich gearbeitet .. – Sachin

1
 

~^/article/(.*)+/(.*)/$~gm 
^ assert position at start of a line 
/article/ matches the characters /article/ literally (case sensitive) 
1st Capturing group (.*)+ 
Quantifier: + Between one and unlimited times, as many times as possible, giving back as needed [greedy] 
Note: A repeated capturing group will only capture the last iteration. Put a capturing group around the repeated group to capture all iterations or use a non-capturing group instead if you're not interested in the data 
.* matches any character (except newline) 
Quantifier: * Between zero and unlimited times, as many times as possible, giving back as needed [greedy] 
/matches the character/literally 
2nd Capturing group (.*) 
Quantifier: * Between zero and unlimited times, as many times as possible, giving back as needed [greedy] 
Note: A repeated capturing group will only capture the last iteration. Put a capturing group around the repeated group to capture all iterations or use a non-capturing group instead if you're not interested in the data 
.* matches any character (except newline) 
Quantifier: * Between zero and unlimited times, as many times as possible, giving back as needed [greedy] 
/matches the character/literally 
$ assert position at end of a line 
g modifier: global. All matches (don't return on first match) 
m modifier: multi-line. Causes^and $ to match the begin/end of each line (not only begin/end of string) 
$re = "~^/article/(.*)+/(.*)/$~m"; 
$str = "/article/xyz/abc/test-string/\n/article/test-string/"; 

preg_match_all($re, $str, $matches); 

Quelle https://regex101.com/

+0

dank Abhijit, diese Erklärung ist wirklich sehr useful.' '~ ^/article/[^ /] */$ ~ '; "löste meinen Zweck – Sachin