0

I'm working to do a "Wiki Game" with PHP, and i'd like to match all the links in a string starting by /wiki/something, for example /wiki/Chiffrement_RSA or /wiki/OSS_117_:_Le_Caire,_nid_d%27espions. I know just a few thigs about REGEX, so I'm struct. If someone could help me, it would be nice. For the time, I just have \/wiki\/*... Thanks for your help !

BDeliers
  • 74
  • 1
  • 12
  • 1
    I would recommend using the strpos as outlined below. But if you want to use a regex, this catches everything up to the first space, then \/wiki\/([^ ]+) works. If you're interested in testing regex's, try http://regexr.com – cody.codes May 22 '17 at 18:21

3 Answers3

2

You can do by regex or strpos:

<?php
$mystring = 'abc';
$find   = '/wiki/';
$statusLink = strpos($mystring, $find);

// Note our use of ===.  Simply == would not work as expected
// because the position of 'a' was the 0th (first) character.
if ($statusLink === false) {
    echo "Not the link that you want";
} else {
    echo "You found the link";
}

 //or by explode
  $link = explode('/', $originalLink);
  if ($link[1] == 'wiki' && isset($link[2])){
    //is your link
  }
?>

I don't use pure regex so much unless it's very necessary.

capcj
  • 1,535
  • 1
  • 16
  • 23
1

You can reduce your output array size by by 50% using \K in your pattern. It eliminates the need for a capture group and puts your desired substrings in the "fullstrings" array.

Pattern:

\/wiki\/\K[^ ]+

\K says "start the fullstring match from here". This means no memory waste. It may be a microimprovement, but I believe it to be best practice and I think more people should use it.

mickmackusa
  • 43,625
  • 12
  • 83
  • 136
0

I finally chose Cody.code's answer with this regex : \/wiki\/([^ ]+). I will use this code to check if i keep a link in an array or not (I will parse my html with DOMDocument an get all the <a>, it's faster) , so the preg_match() solution is the best for me, instead of strpos. Thanks for your help !

BDeliers
  • 74
  • 1
  • 12