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


Replacing specific text pattern from paragraph with php

我需要使用preg_replace或其他方式替换以'Title:'开始并以'Article Body:'结束的文本。替换后的文本将不包含上面的引号。

,

标题:

示例文本1

身体条

示例文本2

应该只输出

示例文本2

如何在php中做到这一点?

使用正反头。

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

上面的正则表达式将替换Title:…文章正文:with '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
)
"
$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);

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