[Solved] search in string from an array of keys. PHP


Please take the UPDATE 2 solution, not first and second result

following code only works if all the key words are exist inside the string. if not. errors will occur.

$str = "I have a sentence like this, and array of some keys.";
$keys = ['have', 'like', 'some'];
$parts = preg_split('/('.implode('|', $keys).')/i', $str);
$parts = array_slice($parts,1);
$result = array_combine($keys, $parts);
print_r($result);

UPDATE not a good solution, but it works:

$str = $modStr = "I have a sentence like this, and array of some keys.";
$keys = ['have', 'like', 'some'];
foreach($keys as $key)
    $modStr = str_replace($key, '[['.$key.']]', $modStr);
echo $modStr."<br>";
preg_match_all('/\[\[([^\]]*)\]\]([^\[]*)/i', $modStr, $parts);
print_r($parts);

UPDATE 2 better solution:

I think this is a better solution. It is a mix of regular expression mixture and string methods:

$str = $modStr = "I have a sentence like this, and array of some keys.";
$keys = ['like', 'have', 'some'];
$positions = [];
// look for each key and be sure it is the whole word (finds only some, not somehow) and save the position in an array.
foreach($keys as $key)
    if(preg_match('/\b'.$key.'\b/i', $str, $m, PREG_OFFSET_CAPTURE))
        $positions[] = [$key, $m[0][1]];
// sort this position array:
usort($positions, function($a, $b) { return $a[1]-$b[1]; });
// now it's easy to split the string, because we have all positions.
$result = [];
for($i=0,$n=count($positions);$i<$n;$i++) {
    $kvPair = $positions[$i];
    $pos = $kvPair[1]+strlen($kvPair[0]);
    $result[$kvPair[0]] = substr($str, $pos,($i+1<$n?$positions[$i+1][1]:strlen($str))-$pos);
}
print_r($result);

this code works also if keys missing in the string and if a key word is followed by special characters.

5

solved search in string from an array of keys. PHP