I am struggling to create a regex to match this:
string: this-string-ends-1c25e41b-f5b2-4484-b5b8-7d45ac2dd427
should return: 1c25e41b-f5b2-4484-b5b8-7d45ac2dd427
ie return everything after the 4th "-" character from the end.
I have tried this:
([^-]*$)
But it just matches from the first. Note the first 3 items (this-string-ends) could be any range of values
With preg_replace
function:
$s = 'this-string-ends-1c25e41b-f5b2-4484-b5b8-7d45ac2dd427';
$result = preg_replace('/.*?([^-]+(?:-[^-]+){4})$/', '$1', $s);
print_r($result);
The output:
1c25e41b-f5b2-4484-b5b8-7d45ac2dd427
Bonus solution with explode
, implode
and array_slice
functions:
$s = 'this-string-ends-1c25e41b-f5b2-4484-b5b8-7d45ac2dd427';
$chunks = explode('-', $s);
$result = (count($chunks) >= 5)? implode('-', array_slice($chunks, -5)) : "";
print_r($result);
The output:
1c25e41b-f5b2-4484-b5b8-7d45ac2dd427
Try the following with preg_match
( DEMO ):
$str = 'this-string-ends-1c25e41b-f5b2-4484-b5b8-7d45ac2dd427';
preg_match('/([^-]+(?:-[^-]+){4})$/', $str, $matches);
var_dump($matches);
Output:
array (size=2)
0 => string '1c25e41b-f5b2-4484-b5b8-7d45ac2dd427' (length=36)
1 => string '1c25e41b-f5b2-4484-b5b8-7d45ac2dd427' (length=36)
Regexless Solution: Here is a solution using implode
, explode
and strrev
:
$str = 'this-string-ends-1c25e41b-f5b2-4484-b5b8-7d45ac2dd427';
$str = strrev($str);
$arr = explode('-', $str, 6);
unset($arr[5]);
$imp = implode('-', $arr);
$matched = strrev($imp);
var_dump($matched);
Output:
string '1c25e41b-f5b2-4484-b5b8-7d45ac2dd427' (length=36)
How about:
$string = 'this-string-ends-1c25e41b-f5b2-4484-b5b8-7d45ac2dd427';
$string = preg_replace('/^.*?-((?:[^-]*-){4}[^-]*)$/', "$1", $string);
echo $string,"\n";
Output:
1c25e41b-f5b2-4484-b5b8-7d45ac2dd427
Use:
[^-]*-[^-]*-[^-]*-[^-]*-[^-]*$
The regex searches for a string which has a string of chars different from '-' ( [^-]*
), followed by -
, followed by the same pattern 4 time, then the string ends ( $
)
Testing on: https://regex101.com/r/49fCit/2 ,the output is:
1c25e41b-f5b2-4484-b5b8-7d45lac2dd427
You want to extract a substring of five groups of hexadecimal characters separated by four hyphens at the end of the string. You can do it with preg_match
:
if ( preg_match('~(?>[^-]+-?\b){5}$~', $str, $m) )
echo $m[0];
You can also be more explicit using [[:xdigit:]]
in place of [^-]
.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.