Str 替换似乎与某些字符串不匹配
我有一个脚本,它接受一些用户输入,清理它并尝试替换字符串中的值。我发现我使用的 str 替换似乎无法匹配,例如 11 +tum
。这是为什么?我可以用某种方式修复它吗? preg Replace 是否管理它,如果是的话,preg Replace 中的情况如何?
功能
该脚本为全文查询准备用户输入字符串,所有单词都是必填的,因此每个空格都替换为空格+。但是像11 tum
这样的短语需要可搜索,因此需要用双引号引起来。失败的部分是脚本似乎无法匹配某些短语,即使在比较之前回显值显示它们是相同的,例如 11 tum
代码:
//processedQuery e.g. 'laptop 11 tum'
$processedQuery = str_replace(" "," +", $processedQuery);
回显已处理的查询; //解析笔记本电脑 +11 +tum
foreach($commonQuery as $value){ //$commonQuery = array("11 tum", "13 tum", "15 tum", "17 tum", "asus eee", "asus 1005","asus 1010")
//compile : simulated query format error
$simulatedErrorValue = str_replace(" "," +",$value);
echo simulatedErrorValue; //parses 11 +tum
$processedQuery = str_replace($simulatedErrorValue,'"'.$value.'"',$processedQuery);
}
echo $processedQuery; //解析笔记本电脑+11+tum //将 11 tum 交换为 asus eee(另一个 commonQuery 和 $processedQuery 的最后一个回显显示正确的 laptop +"asus eee"
I have a script which takes in some user input, cleans it and tries to replace the value in a string. I found that the str replace that I use cant seem to match e.g. 11 +tum
. Why is that? Can I fix it some way? Does preg replace manage it, and if so how does that look in preg replace?
Function
The script prepares the user input string for a full text query, all words are mandatory so each space is replaced with space+. But some phrases like 11 tum
need to be searchable and thus put in double quotes. The failing part is that the scirpt cant seem to match some phrases even though echoing the valus before comparison shows they are the same, e.g. 11 tum
Code:
//processedQuery e.g. 'laptop 11 tum'
$processedQuery = str_replace(" "," +",$processedQuery);
echo processedQuery; //parses laptop +11 +tum
foreach($commonQuery as $value){ //$commonQuery = array("11 tum", "13 tum", "15 tum", "17 tum", "asus eee", "asus 1005","asus 1010")
//compile : simulated query format error
$simulatedErrorValue = str_replace(" "," +",$value);
echo simulatedErrorValue; //parses 11 +tum
$processedQuery = str_replace($simulatedErrorValue,'"'.$value.'"',$processedQuery);
}
echo $processedQuery; //parses laptop +11 +tum
//exchange 11 tum for asus eee (the other commonQuery and the last echo of $processedQuery shows the correct laptop +"asus eee"
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您混淆了函数的输入。我通过一个小修改得到了所需的结果:
您的错误是这一行:
这是一个只有 1 个成员的数组。
您想要将数组更改为有 2 个成员:
这是我的完整代码:
You are confusing the input to your function. I'm getting the desired result with a small modification:
Your error is this line:
This is an array with just 1 member.
You want to change the array to have 2 members:
Here is my full code: