I want to find the string from
$str = "Hello this is dummy.test. in this string
any character, any special character can appear. it is not a fixed type
text and predefined. this string will not read manually check by the
Programmer.Sorry for the bad English.";
my algo is fixed because some kind of problem. First I want to find the position of test keyword then want to go back from test to dummy keyword to find position of dummy keyword .
I also searched and also use the internet but no any function found in PHP which can traverse back in this way.
I also test strrpos()
but not relevant and required result. Any solution please.
Output needed : dummy.test
Algo : find first right (test) and then right to left (dummy) only. not first right (test) and then from starting to left (dummy) .
strrpos
Would be the right way. If I understand you correctly, this should work, using the offset parameter:
$test = strrpos($str, 'test');
$dummy = strrpos($str, 'dummy', $test);
This will find the last "dummy" that occurs before the last "test".
First find the position of test
using strpos()
, cut the string up until test
with substr()
, and then use strpos()
again to find the position of dummy
in the substring:
$substring = substr($str, 0, strpos($str, 'test'));
$dummy = strpos($substring, 'dummy');
echo $dummy;
Output:
14
UPDATE
As per the question edit, the following function should do what you want. It's probably not the best solution and is a bit ugly, but that should get you started:
function searchstr($str)
{
$pos = strpos($str, 'test') + strlen($str);
$substring = substr($str, 0, $pos);
$dummypos = strpos($substring, 'dummy', TRUE);
$words = explode(' ', $str);
$chars = -1;
foreach($words as $word)
{
$chars += strlen($word);
if($chars >= $dummypos)
{
return $word;
}
}
return '';
}
echo searchStr($str);
Output:
dummy.test.