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

用php替换段落中的特定文本模式,php,replace,preg-replace,design-patterns,Php,Replace,Preg Replace,Design Patterns,我需要使用preg_replace或其他方式替换以“Title:”开头、以“Article Body:”结尾的文本。替换的文本将不包含上述引用的单词 例如: 标题: 示例文本1 第条正文: 示例文本2 应该只输出 示例文本2 如何使用php实现这一点 $str = 'Title: this is sample text Article Body: this is also sample text'; // output: this is sample text this is also sam

我需要使用preg_replace或其他方式替换以“Title:”开头、以“Article Body:”结尾的文本。替换的文本将不包含上述引用的单词

例如:

标题:

示例文本1

第条正文:

示例文本2

应该只输出

示例文本2

如何使用php实现这一点

$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);
正则表达式非常有用,您应该学习如何使用它。网上有很多文章,也有这个
我可以帮你

使用正面/负面表情

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

$result=preg\u replace('/(?听起来很简单。到目前为止您尝试了什么?我知道可以用preg_replace来完成。但是我没有使用regex的经验。谢谢!但是这不起作用。我需要用没有文本的模式来替换它。@AmilaPremasiri:从第二个参数中删除“$2”。它可以用字符串文字作为替换参数吗(
“$1$2”
位)?我一直认为它必须是一个非文本字符串(例如
“$1$2”
)。对不起,文本结构中应该有下排。结构类似于本文
"
(?<=                # 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
)
"