0

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.

BlitZ
  • 12,038
  • 3
  • 49
  • 68

3 Answers3

2

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.

BlitZ
  • 12,038
  • 3
  • 49
  • 68
  • Why need a callback? Wouldn't `preg_replace` and as replacement `'\0'` be convenient? – Jonny 5 Aug 27 '14 at 10:44
  • It gets rendered in browser just like this : < Jens > is my name. I play < Football >. I saw < Steffy > Yesterday. Yeah, We will be < Together > For sure. No bold! – Maxin Bits Aug 27 '14 at 10:45
  • @Jonny5 I do have a strong feeling, that after this "Find & Replace" OP might want to have more control over situation. – BlitZ Aug 27 '14 at 10:45
  • @MaxinBits remove `header()` string – BlitZ Aug 27 '14 at 10:46
  • @MaxinBits Yea, maybe OP want to use `htmlspecialchars` for the stuff inside `...` :) – Jonny 5 Aug 27 '14 at 11:01
2

You can use this preg_replace:

$repl = preg_replace('/(<[^>]*>)/', '<b>$1</b>', $str);

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

RegEx Demo

anubhava
  • 761,203
  • 64
  • 569
  • 643
1

For Much better understanding and learning regex for the further work you can visit the below links

Learning Regular Expressions

Useful regular expression tutorial

Regular expressions tutorials

And one of the best and easy one and my favourite is

http://www.9lessons.info/2013/10/understanding-regular-expression.html?utm_source=feedburner&utm_medium=email&utm_campaign=Feed%3A+9lesson+%289lessons%29

very nice and easy tutorial for the beginners

Community
  • 1
  • 1
Veerendra
  • 2,562
  • 2
  • 22
  • 39