0

I think that one of the common uses of preg_replace is to replace a pattern enclosed by delimiters such as parenthesis(), square brackets [], curly brackets{}, angle brackets<>, double quotes "", single quotes ``, ...

What I learned from the PHP site is that often used delimiters are forward slashes (/), hash signs (#) and tildes (~). This is confusing either after testing some replacements

For Example

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');

I need to know

  1. How to change this code so that I could replace text between double quotes "" and angle quotes<>
  2. What is the difference between using

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

and

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

For single quotes delimiters.

  1. How to escape these delimiters (using a backslash for example) so that they are not treated as special characters?
Hamed
  • 159
  • 8
  • 1
    `(.*?)` - matches anything "non-greedy" none or more, `([^']*)` anything not `'` none or more. – ArtisticPhoenix Mar 06 '19 at 22:31
  • 1
    `is that often used delimiters are forward slashes (/), hash signs (#) and tildes (~)` these are delimiters for the regex. `/(.*?)/` , `#(.*?)#` or `~(.*?)~` you can use anything you want for these as long as they dont have special meaning in regex (like `?` or `+` have special meaning) and you have to escape any occurrence of the delimiter in the pattern, so most people use something not in the pattern. For example if you use a URL `yourdomain.com/foo` you may not want to use `/` as the denim because it naturally appears in the pattern, so we need to escape it `/yourdomain.com\/foo/` – ArtisticPhoenix Mar 06 '19 at 22:39
  • Be aware that preg_replace also replaces your delimiters and not the stuff that is between them (i dont mean the forward slashes at the beginning and end of the regex string) – Natha Mar 06 '19 at 22:40

0 Answers0