Preg_match lookbehind after second slash

This is my line:

stringa/stringb/123456789,abc,cde

and after preg_match:

preg_match('/(?<=\/).*?(?=,)/',$array,$matches);

:

stringb/123456789

How can I change preg_match to retrieve a string after the second slash (or after the last slash)?

Required Conclusion:

123456789
+4
source share
3 answers

You can compare all except /as

/(?<=\/)[^\/,]*(?=,)/
  • [^\/,]*A negative character class matches any other than ,or\

Regex Demo

Example

preg_match('/(?<=\/)[^\/,]*(?=,)/',$array,$matches);
// $matches[0]
// => 123456789
+4
source

That should do it.

<?php
$array = 'stringa/stringb/123456789,abc,cde';
preg_match('~.*/(.*?),~',$array,$matches);
echo $matches[1];
?>

Do not count everything to the last slash ( .*/). After finding the last slash, save all data to the first comma ( (.*?),).

+2
source

You do not need to use lookbehind, i.e.:

$string = "stringa/stringb/123456789,abc,cde";
$string = preg_replace('%.*/(.*?),.*%', '$1', $string );
echo $string;
//123456789

Demo:

http://ideone.com/IxdNbZ


Regex Explanation:

.*/(.*?),.*

Match any single character that is NOT a line break character «.*»
   Between zero and unlimited times, as many times as possible, giving back as needed (greedy) «*»
Match the character "/" literally «/»
Match the regex below and capture its match into backreference number 1 «(.*?)»
   Match any single character that is NOT a line break character «.*?»
      Between zero and unlimited times, as few times as possible, expanding as needed (lazy) «*?»
Match the character "," literally «,»
Match any single character that is NOT a line break character «.*»
   Between zero and unlimited times, as many times as possible, giving back as needed (greedy) «*»

$1

Insert the text that was last matched by capturing group number 1 «$1»
0
source

All Articles