Match string containing two "needles"
3 answers
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
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
source to share