I am trying to discuss within your code. I hope its will help
<?php
$text = 'abc def abc ghi abc jkl';
$search = 'abc';
$regex = '/'.trim($search).'/ism';
if(preg_match_all($regex, $text, $tmp))
{
$array_key = $tmp[0];
/*Test using print_r($tmp);
then you will find result: Array( [0] => Array ( [0] => abc [1] => abc [2] =>
abc) )
If you want to test/print first array value then echo $array_key[0]; result is: abc
Similarly for $array_key[1] or $array_key[2] result is abc
That means your array contains 3 same value
*/
foreach($array_key as $ak)
{
/*If you use echo $ak[1]; then it will print b because in foreach loop $ak value
is: abc
You can't print only abc in foreach loop. To print abc you don't need to use
foreach loop. Just use echo $array_key[0];
*/
}
}
?>
Maybe your expected code is:
<?php
$text = 'abc def abc ghi abc jkl';
$search = 'abc';
$regex = '/'.trim($search).'/ism';
if(preg_match_all($regex, $text, $tmp))
{
$array_key = $tmp[0];
echo $array_key[0];
}
?>
Output: abc