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.

1
  • try <[^<>]*> regex. Commented Aug 27, 2014 at 10:39

3 Answers 3

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.

Sign up to request clarification or add additional context in comments.

5 Comments

Why need a callback? Wouldn't preg_replace and as replacement '<b>\0</b>' be convenient?
It gets rendered in browser just like this : <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. No bold!
@Jonny5 I do have a strong feeling, that after this "Find & Replace" OP might want to have more control over situation.
@MaxinBits remove header() string
@MaxinBits Yea, maybe OP want to use htmlspecialchars for the stuff inside <b>...</b> :)
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

3 Comments

\b or <b>? I'm on browser not in CLI.
Yes that's correct, my HTML skills are pretty poor :(
its ok..np..Cheers..:)
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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.