用php替换段落中的特定文本模式

时间:2011-11-05 08:58:58

标签: php replace preg-replace design-patterns

我需要使用preg_replace或其他方式替换以'Title:'开头并以'Article Body:'结尾的文本。替换的文字不会包含上面引用的单词。

例如:

名称:

示例文本1

文章正文:

示例文本2

只能输出

示例文本2

我怎么能用PHP做到这一点?

2 个答案:

答案 0 :(得分:0)

$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也可以帮到你。

答案 1 :(得分:0)

使用正面/负面前瞻。

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

以上正则表达式将取代标题内的任何内容:...文章正文:使用\ 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
)
"