Match string containing two "needles"
I have a line that looks something like this:
1: u:mads g:folk 2: g:andre u:jens u:joren
what i need is a way (i assume regex) to get for example u: jens and a number (1 or 2) after.
how do i do this in php (preferably with only one function)?
+3
Zlug
source
to share
3 answers
All matches will be found here. If you only want the former, use preg_match
.
<?php
$subject = '1: u:mads g:folk 2: g:andre u:jens u:joren 3: u:jens';
preg_match_all('#(\d+):[^\d]*?u:jens#msi', $subject, $matches);
foreach ($matches[1] as $match) {
var_dump($match);
}
?>
+2
Aram kocharyan
source
to share
You can use the following regex:
(\d+):(?!.*\d+:.*).*u:jens
If the number you want fits into the first capture group. So, if you are using PHP:
$matches = array();
$search = '1: u:mads g:folk 2: g:andre u:jens u:joren';
if (preg_match('/(\d+):(?!.*\d+:.*).*u:jens/', $search, $matches)) {
echo 'Found at '.$matches[1]; // Will output "Found at 2"
}
0
Xophmeister
source
to share
This will parse the string and return an array containing the numeric keys in which the search string was found:
function whereKey($search, $key) {
$output = array();
preg_match_all('/\d+:[^\d]+/', $search, $matches);
if ($matches[0]) {
foreach ($matches[0] as $k) {
if (strpos($k, $key) !== FALSE) {
$output[] = (int) current(split(':', $k));
}
}
}
return $output;
}
For example:
whereKey('1: u:mads g:folk 2: g:andre u:jens u:joren', 'u:jens')
... will return:
array(1) { [0]=> int(2) }
0
Xophmeister
source
to share