Powered by Blogger.

PHP regular to replace conetent between two tags


The following regular for PHP is to replace the content between two tags.

$pattern = '/<td>(.*?)<\/td>/s';
$html = '<tr><th>Title</th><td>Gravity Forms</td></tr>';
if( $html = preg_replace( $pattern, '<td>Formidable Forms</td>', $html ) ){
    echo $html;
}

As/in regular has special definition so there’s a \ used as escapes character.

From the above we may replace URL in HTML link as the following:


$pattern = '/href="(.*?)"/s';
$html = 'Please visitor <a href="https://waytowp.com">waytowp.com...</a>';
$matches = array();

if( $html = preg_replace( $pattern, 'href="http://gravityforms.com"', $html ) ){
    echo $html;
}

No comments