【问题标题】:Replacing specific text pattern from paragraph with php用php替换段落中的特定文本模式
【发布时间】:2011-11-05 08:58:58
【问题描述】:

我需要使用 preg_replace 或其他方式替换以“标题:”开头并以“文章正文:”结尾的文本。被替换的文本不会包含上面引用的单词。

例如:

标题:

示例文本 1

文章正文:

示例文本 2

应该只输出

示例文本 2

我怎样才能用 php 做到这一点?

【问题讨论】:

  • 听起来很简单。到目前为止你尝试过什么?
  • 我知道可以使用 preg_replace 来完成。但我没有使用正则表达式的经验。

标签: php replace preg-replace design-patterns


【解决方案1】:

使用正/负前瞻。

$result = preg_replace('/(?<=Title:).*(?=Article Body:)/s', '\nTest\n', $subject);

上面的正则表达式将替换 Title: ... Article Body: 中的任何内容 \nTest\n

解释:

"
(?<=                # Assert that the regex below can be matched, with the match ending at this position (positive lookbehind)
   Title:              # Match the characters “Title:” literally
)
.                   # Match any single character
   *                   # Between zero and unlimited times, as many times as possible, giving back as needed (greedy)
(?=                 # Assert that the regex below can be matched, starting at this position (positive lookahead)
   Article\ Body:      # Match the characters “Article Body:” literally
)
"

【讨论】:

    【解决方案2】:
    $str = 'Title: this is sample text Article Body: this is also sample text';
    
    // output: this is sample text this is also sample text
    echo preg_replace('~Title: (.*)Article Body: (.*)~', '$1 $2', $str);
    

    正则表达式非常有用,你应该学会如何使用它。网上有很多文章,还有这个summarize 可以帮你。

    【讨论】:

    • 谢谢!但这不起作用。我需要用无文本替换此模式。
    • @AmilaPremasiri:从第二个参数中删除`$2`。
    • 它是否可以使用字符串文字作为替换参数('$1 $2' 位)?我一直认为它必须是一个非文字字符串(例如"$1 $2")。
    • 对不起,文本结构中应该有下划线。结构就像这篇文章realorscam.com/big-brother-7-%E2%80%93-grace-is-evicted.html
    猜你喜欢
    • 1970-01-01
    • 2016-02-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-25
    • 2018-03-24
    相关资源
    最近更新 更多