【问题标题】:preg_replace for replacing everything of a variablepreg_replace 用于替换变量的所有内容
【发布时间】:2024-03-08 17:20:02
【问题描述】:

我实际上遇到了问题,在我的情况下,我选择 来自 MYSQL 数据库的信息保存到 $data 中。

我有 2 个用于 preg_replace 的数组。

这是一个例子:

$repl();
$repl[0] = '/bull/';
$repl[1] = '/found/';
$repl[2] = '/search/';

$replto();
$replto[0] = 'This is not a ballon';
$replto[1] = 'This has been found';
$replto[2] = 'Im looking for it';

$data = array();
$data[0] = '/mynickname/search';
$data[1] = '/somebulls/search';
$data[2] = '/mcdo/found';
$data[3] = '/bump/search';
$data[4] = '/blood/bull';

echo preg_replace($repl,$replto,$data);

好的,但是 preg_replace 的输出是这样的:

/mynickname/Im looking for it
/somebulls/Im looking for it
/mcdo/This has been found
/bump/Im looking for it
/blood/This is not a ballon

...但我想要这个输出:

Im looking for it
Im looking for it
This has been found
Im looking for it
This is not a ballon

我是php新手,我解决了很多问题,但这是一个我还没有找到解决方案的问题。

你能帮帮我吗?

【问题讨论】:

  • strrpos (php.net/strrpos) 和 substr (php.net/substr) 的组合应该很容易做到这一点。
  • 好吧,代码完全按照你的方式工作......我认为你的逻辑在这里不正确。如果searchIm looking for it 替换,为什么你会认为/mynickname/search 会自动删除mynickname 部分?它只是替换你告诉它的部分。
  • 哇...容易吗?...不适合我,我认为这只是在“preg_replace”中添加的事件...就像在 SQL 中使用 LIKE 中的 % 时一样。
  • 是的@charlie74,你说得对,我希望我能找到一种方法来获取数组 $data 的整行,因为我为用户编辑视觉对象,他们不想看到路径(例如:/mcdo/)

标签: php arrays string preg-replace


【解决方案1】:

非常感谢它完美地工作。

点赞

$repl();
$repl[0] = '/.*bull/';
$repl[1] = '/.*found/';
$repl[2] = '/.*search/';

抱歉回复晚了,不能早点来。

再次感谢。

【讨论】:

    【解决方案2】:

    根据您想要的结果,您似乎想要执行以下操作:

    $repl();
    $repl[0] = '/.*bull/';
    $repl[1] = '/.*found/';
    $repl[2] = '/.*search/';
    

    【讨论】:

    • /* 将出现 0 次或多次 /。这不是你要找的。然后最重要的是, / 被用作模式分隔符,所以 * 真的不知道适用于什么。
    • 非常感谢,它运行良好。不能投票给那个答案:/我没有声誉。现在我可以:)
    最近更新 更多