搜索并替换随机单词


Search and replace random word

好吧,首先让我说,在发布这个之前,我已经测试了很多东西,很多次,但目前,我实际上不知道还能做什么,因为没有什么适合我。

这是我目前拥有的代码:

<?php
// These are the arrays given by the application. All of them has an "%s" within.
// For example...
$arrs = array(
    "this is a %s array" => "converted1 %s text", 
    "value %s test" => "converted2 %s text", 
    "test %s test" => "converted3 %s text"
); 
$text = "This is a random text. Which can contains or not some of the expressions listed above. In this case it contains this: this is a magic array, value hey test, test php test";
// The output should be:
// "This is a random text. Which can contains or not some of the expressions listed above. In this case it contains this: CONVERTED magic TEXT, CONVERTED2 hey TEXT, CONVERTED3 php TEXT"
foreach($arrs as $k => $v){
    // Seriously, I don't know what's next here... also I'm thinking this foreach is not right here.
}
?>

主要目标是在文本框输入中随机编写一些内容。所以我在文本框中检查是否已填充某些数组键($arrs)。问题是我无法使用strpos检测到它,因为 %s 总是随机的,所以找到它的位置有点困难......

假设我写"这是一个随机数组"(它在数组中),所以如果我们检查它的值,我们会看到它将是"转换1 RANDOM文本"。

我已经测试过使用模式,也测试了explode();preg_replace_callback,但没有任何效果。这真的让我发疯了...

非常感谢你们。

使用正则表达式。

<?php
$pattern = '~this is a ([^ ]*) array~U';
$replace = 'converted1 $1 text';
$text = preg_replace($pattern,$replace,$text);

您已经有 ASSoc 数组,您可以将键更改为正则表达式和值以替换字符串(使用转义组,如上面的 $1)。同样在foreach()中,您可以先检查:

<?php
if (preg_match($k,$text)) {
    // do the replacing here
}

注意:我用 [^ ]* 来匹配单个单词。这不仅是方法,可能不是最好的方法。你也可以使用 ''w,但我个人不喜欢它:)

编辑:

在这里,您可以使用可用的现成代码(刚刚在我的 XAMPP 上对其进行了测试)

<?php
$arrs = array(
    "~this is a ([^ ]*) array~U" => "converted1 $1 text", 
    "~value ([^ ]*) test~U" => "converted2 $1 text", 
    "~test ([^ ]*) test~U" => "converted3 $1 text"
); 
$text = "This is a random text. Which can contains or not some of the expressions listed above. In this case it contains this: this is a magic array, value hey test, test php test";
foreach($arrs as $k => $v){
    if (preg_match($k,$text)) {
        $text = preg_replace($k,$v,$text);
    }
}
?>