gpt4 book ai didi

php - 使用 preg_replace 替换 php 中所有出现的地方

转载 作者:可可西里 更新时间:2023-11-01 01:09:23 25 4
gpt4 key购买 nike

正则表达式绝对是我的弱点,这个让我完全难住了。我正在构建一个相当基本的搜索功能,我需要能够根据以下模式更改我的用户输入:

主题:

%22first set%22 %22second set%22-drupal -wordpress

期望的输出:

+"first set" +"second set" -drupal -wordpress

我希望我能提供更多帮助,因为我通常喜欢至少发布目前为止的解决方案,但在这个问题上我不知所措。

感谢任何帮助。谢谢。

最佳答案

您的数据似乎是经过 URL 编码的。如果你申请urldecode , 你会得到

"first set" "second set" -drupal -wordpress

(我假设您在 -drupal 之前有一个空格)。

现在您必须添加+。同样,我假设您必须在所有没有 - 且不在引号内的单词之前添加这些:

$str = '"first set" "second set" -drupal -wordpress foo';
echo preg_replace('#( |^)(?!(?:\w+"|-| ))#','\1+', $str));
// prints +"first set" +"second set" -drupal -wordpress +foo

更新:如果您不能使用urldecode,您可以使用str_replace%22替换为

关于php - 使用 preg_replace 替换 php 中所有出现的地方,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4643442/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com