【问题标题】:Replace content between two words [duplicate]替换两个单词之间的内容[重复]
【发布时间】:2012-09-21 18:37:09
【问题描述】:

我正在尝试使用 php 替换两个单词之间的内容。这两个词之间的内容不同,所以我不能使用传统的str_replace。我想替换两个单词之间的内容,例如:

I would like to replace **some string of text** between two words

改为:

I would like to replace between two words

您可以看到我删除了“一些”和“文本”之间的所有措辞。同样,我不能使用常规的 str_replace,因为这两个词之间的文本可能不同。例如它可能会说:

I would like to replace **some words of text** between two words

改为:

I would like to replace between two words

【问题讨论】:

  • $txt = preg_quote('some string of text'); $new = preg_replace("/$txt/", 'new text', $old); 不起作用?

标签: php str-replace


【解决方案1】:

正则表达式很简单:/some .*? text/

只需将其替换为空字符串即可。

【讨论】:

  • 非常感谢。这很完美。
【解决方案2】:

根据您的问题,只有字符串的内部部分发生了变化。如果是这种情况,那就很简单了,因为你已经有了解决方案:你不需要替换它,但你只需要不接管它:

$result = substr($string, 0, $startlen) . substr($string, -$endlen);

这可能有助于您为此类问题找到更多“分辨率角度”。

【讨论】:

    猜你喜欢
    • 2019-11-14
    • 1970-01-01
    • 1970-01-01
    • 2012-05-28
    • 2019-05-04
    • 1970-01-01
    • 1970-01-01
    • 2019-02-07
    • 2019-11-04
    相关资源
    最近更新 更多