如何使用preg_replace替换不同定界符(){} [] <>之间的文本,以及如何在需要时转义这些定界符?

时间:2019-03-06 22:29:41

标签: php preg-replace

我认为preg_replace的常见用法之一是替换由定界符包围的模式,例如括号(),方括号[],花括号{},尖括号<>,双引号"",单引号``,...

我从PHP site中学到的是,经常使用的定界符是正斜杠(/),哈希符号(#)和波浪号(〜)。在测试了一些替代品之后,这令人困惑

例如

function replace_delimiters($text) {
    $text = preg_replace('/\((.*?)\)/', 'This replaces text between parenthesis', $text);  //working
    $text = preg_replace('/\[(.*?)\]/', 'This replaces text between square brackets', $text);  //working
    $text = preg_replace('/`([^`]*)`/', 'This replaces the text between single quotes', $text);  //working 
    $text = preg_replace('/\`(.*?)\`/', 'This replaces the text between single quotes', $text); //working
    $text = preg_replace('/(?<!\\\\)`((?:[^`\\\\]|\\\\.)*)`/', 'This replaces the text between single quotes', $text); //working
    $text = preg_replace('/\<(.*?)\>/', 'This replaces the text between angle quotes', $text);   // Not working
    $text = preg_replace('/"[^"]*"/', 'This replaces the text between double quotes', $text);   // Not working

    return $text;
}
add_filter('the_content', 'replace_delimiters');
add_filter( 'the_excerpt', 'replace_delimiters');

我需要知道

  1. 如何更改此代码,以便我可以在双引号""和尖引号<>之间替换文本
  2. 使用之间有什么区别

    '/`([[^`] *)`/'

'/\`(.*?)\`/'

用于单引号分隔符。

  1. 如何转义这些定界符(例如,使用反斜杠),以便不将其视为特殊字符?

0 个答案:

没有答案