0

我有以下字符串替换问题,我在这里得到了很好的解决

PFB 样本字符串

$string = 'The quick sample_text_1 56 quick sample_text_2 78 fox jumped over the lazy dog.';

$patterns[0] = '/quick/';
$patterns[1] = '/quick/';
$patterns[2] = '/fox/';

$replacements[2] = 'bear';
$replacements[1] = 'black';
$replacements[0] = 'slow';

echo preg_replace($patterns, $replacements, $string);   

我需要根据我发送的号码替换“快速”

即,如果我对函数的输入是56,则需要将quick之前56替换为bear,如果我对函数的输入是78,则需要将快速之前78替换为black

有人可以帮我吗?

4

4 回答 4

1

我认为正则表达式会使这变得困难,但你应该能够只使用strpos(),substr()str_replace().

  • 用于strpos在 56 和 78 的字符串中查找位置。

  • 然后在这些点使用 将字符串切割成子字符串substr

  • 现在,将 'quick' 替换为正确的变量,具体取决于将 56 还是 78 发送到函数以及您正在处理的子字符串。

于 2009-04-10T13:16:18.783 回答
0

而不是使用preg_replace,用于substr_replace进行字符串替换和strpos根据您传递的参数在字符串中查找起点和终点。您的模式是一个简单的字符串,因此它不需要正则表达式,并且 substr_replace 将允许您在字符串中指定起点和终点以进行替换(这似乎是您正在寻找的)。

编辑:

根据您的评论,听起来您必须进行大量检查。我没有测试过这个,所以它可能有一两个错误,但试试这样的函数:

function replace($number, $pattern, $replacement)
{
    $input = "The quick sample_text_1 56 quick sample_text_2 78 fox jumped over the lazy dog.";
    $end_pos = strpos($input, $number);
    $output = "";
    if($end_pos !== false && substr_count($input, $pattern, 0, $end_pos))
    {
        $start_pos = strrpos(substr($input, 0, $end_pos), $pattern);
        $output = substr_replace($input, $replacement, $start_pos, ($start_pos + strlen($pattern)));
    }
    return $output;
}

此函数执行以下操作:

  1. $end_pos !== false首先,检查字符串 ( )中是否存在“数字”参数
  2. 检查您的模式在字符串开头和数字位置之间是否存在至少一次 ( substr_count($input, $pattern, 0, $end_pos))
  3. 使用strrpos函数获取模式在子字符串中最后一次出现的位置
  4. 使用模式的起始位置和长度插入替换字符串substr_replace
于 2009-04-10T13:15:58.080 回答
0

你做错了。相反,根据您的函数输入,您应该使用正确的查找和替换值。只需根据您的函数输入值创建查找和替换值的映射。喜欢:

$map = array(
  56 => array('patterns' => array(), 'replacements' => array()),
  78 => array(...)
);
于 2009-04-10T13:20:19.177 回答
0

尝试这个:

$searchArray = array("word1", "sound2", "etc3");
$replaceArray = array("word one", "sound two", "etc three");
$intoString = "Here is word1, as well sound2 and etc3";
//now let's replace
print str_replace($searchArray, $replaceArray, $intoString);
//it should print "Here is word one, as well sound two and etc three"
于 2013-09-19T07:46:02.333 回答