0

我想从中找到字符串

$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.";

我的算法是固定的,因为某种问题。首先我想找到test关键字的位置,然后想从test回到dummy关键字来找到dummy关键字的位置。

我也搜索并使用了互联网,但在 PHP 中找不到任何可以以这种方式遍历的函数。

我也测试strrpos()但不相关和必需的结果。请提供任何解决方案。

需要输出dummy.test

算法首先找到右(测试),然后从右到左(虚拟)。不是先右(测试),然后从开始到左(虚拟)。

4

2 回答 2

1

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

Demo!


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.

Demo!

于 2013-09-19T16:40:00.213 回答
0

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".

于 2013-09-19T16:35:17.343 回答