Maxin Bits Maxin Bits - 15 days ago 6
PHP Question

PHP regex to Find & Replace specific string

Well,

I've some texts like this below:


< Jens > is my name. I play < Football >. I saw < Steffy > Yesterday. Yeah, We will be < Together > For sure.


And I just want all the texts between '<' & '>' (including <>) to be bold programmatically using Regular Expression (Preferably) or any other method. This is a kind of Find & Replace. So after the operation texts should be :


< Jens > is my name. I play < Football >. I saw < Steffy > Yesterday. Yeah, We will be < Together > For sure.

Answer

Use preg_replace_callback():

<?php
// header('Content-Type: text/plain; charset=utf-8');

$test = <<<TXT
< Jens > is my name. I play < Football >.
I saw < Steffy > Yesterday. Yeah, We will be < Together > For sure.
TXT;

$result = preg_replace_callback(
    '/<[^>]+>/',
    function($matches){
        return '<b>' . htmlspecialchars($matches[0]) . '</b>';
    },
    $test
);

print_r($result);
?>

Output:

< Jens > is my name. I play < Football >. I saw < Steffy > Yesterday. Yeah, We will be < Together > For sure.