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
- How to change this code so that I could replace text between double quotes
""
and angle quotes<>
What is the difference between using
'/`([^`]*)`/'
and
'/\`(.*?)\`/'
For single quotes delimiters.
- How to escape these delimiters (using a backslash for example) so that they are not treated as special characters?