php-regexHow to replace a tag using PHP regex?
Regex (Regular Expressions) can be used to replace tags in PHP.
$string = 'This is a <b>bold</b> string';
$string = preg_replace('/<b>(.*?)<\/b>/', '<strong>$1</strong>', $string);
The output of the above code will be:
This is a <strong>bold</strong> string
The code consists of three parts:
$stringis the string that contains the tag to be replaced.preg_replaceis a PHP function that performs a regular expression search and replace. The first argument is the regular expression pattern to search for, the second argument is the replacement string, and the third argument is the string to search.$1is a backreference to the first captured group in the regular expression pattern.
Helpful links
More of Php Regex
- How to use PHP regex to get a YouTube video ID?
- How to use PHP regex to match a nbsp HTML whitespace?
- How to use PHP regex to match special characters?
- How to use PHP regex to match an exact string?
- How to use PHP regex to match a multiline?
- How to use PHP regex to match a year?
- How to use PHP regex to match time?
- How to use regex in PHP to match date in "yyyy-mm-dd" format?
- How to use PHP regex to match an XML tag?
- How to get the first match when using regex in PHP?
See more codes...