如何跳过strrpos Entry

时间:2017-10-21 20:19:48

标签: php string

是否可以跳过strpos / strrpos位置?

    $string = "This is a cookie 'cookie'.";
    $finder = "cookie";
    $replacement = "monster";
    if (strrpos($string, $finder) !== false)
        str_replace($finder, $replacement, $string);

我想跳过' cookie'并更换普通饼干,这样就会导致"这是一个怪物' cookie'。"

我没有对它发现' cookie'首先然后检查它(显然有必要确定它不应该被替换),但我想确保在“' cookie'仍然存在,我可以使用相同的功能来查找未加引号的cookie。

或者,是否有一个函数我还没有找到(通过几小时的搜索)来获取特定单词的所有索引,所以我可以通过循环检查它们而不使用正则表达式?

重要的是它是索引,而不是单词本身,因为还有其他检查需要根据单词的位置在字符串中的位置进行。

3 个答案:

答案 0 :(得分:2)

您可以尝试使用正则表达式:

尝试以下方法:

$string = "This is a cookie 'cookie'.";

var_dump(preg_replace("/(?<!')(cookie)/", ' monster', $string));

这使用preg_replace代替str_replace来替换字符串。

修改:您可以使用preg_match获取匹配的正则表达式在字符串中的位置,如:

$string = "This is a cookie 'cookie'.";
$finder = "cookie";
preg_match("/(?<!')(" . preg_quote($finder) . ")/", $string, $matches, PREG_OFFSET_CAPTURE);
var_dump($matches);

您可以使用preg_quote确保preg_matchpreg_replace不将$finder var视为regex。并且preg和php中的其他字符串函数之间的性能差异非常微妙。您可以运行一些基准测试,看看它的情况会有所不同。

答案 1 :(得分:1)

以下给出了所需的替换以及替换单词的位置。

$string = "This is a cookie 'cookie'."; 
$finder = "cookie";
$replacement = "monster";
$p = -1; // helps get position of current word
$position = -1; // the position of the word replaced
$arr = explode(' ',$string);
for($i = 0; $i < count($arr); $i += 1){
// Find the position $p of each word and
// Catch $position when a replacement is made
if($i == 0){$p = 0;} else {  $w =$arr[$i - 1]; $p  += strlen($w) + 1;}
if($arr[$i] == $finder){ if($position < 0){$position = $p;}$arr[$i] = $replacement;}}
$newstring = implode(' ', $arr);
echo $newstring; // gives: This is a monster 'cookie'
echo '<br/>';
echo $position;  // gives 10, the position of replaced element.

对于该位置,假设该句子只有单个空格,因为在explodeimplode函数中使用了空格。否则,需要修改双重或更大空间的情况,可能需要用@$#作为explode和{{1}的第一个参数的唯一字符或字符集替换空格。函数。

可以修改代码以捕获多个替换,例如通过捕获数组中的每个替换位置而不是测试implode。这还需要更改if(position < 0)的计算方式,因为它的值会受到先前替换长度的影响。

答案 2 :(得分:1)

我们也可以这样做,为了简短:

还包括函数str_replace的前一个字母,如下所示:

$string = "This is a cookie 'cookie'.";
echo str_replace('a cookie','a monster',$string);
相关问题