timo
timo

Reputation: 95

php replace string to html tag

I want to display content in a php page from a .txt and change some tag to a html code like the following using:

Change this:

[img: something.jpg]

To this:

<img src="something.jpg" />  

I've tried to use preg_replace, but I have no idea how to use those symbols like /(){}^*.:. What it means to use things like this to extract some variables $1 $2 from a string?

$string = 'April 15, 2003';
$pattern = '/(\w+) (\d+), (\d+)/i';

Upvotes: 1

Views: 640

Answers (2)

Rasclatt
Rasclatt

Reputation: 12505

@Uchiha has a great regex (+1 for it!), but you may want to use a preg_replace_callback() instead if you are wanting to use it for a [shortcode] type application:

function shortcode($val = false)
    {
        return (!empty($val))? preg_replace_callback('/\[(\w+):\s?(\w+.\w+)]/',function($matches) {
                if(!empty($matches[2])) {
                        switch($matches[1]) {
                                case ('img'):
                                    return '<img src="'.$matches[2].'" />';
                            }
                    }
            },$val) : false;
    }

echo shortcode('[img: something.jpg]');

Upvotes: 2

Narendrasingh Sisodia
Narendrasingh Sisodia

Reputation: 21422

You can use the following regex like as

\[(\w+):\s?(\w+.\w+)]

Regex Explanation

  • \[ : \[ will check for [ literally.
  • (\w+): : (\w+) Capturing groups of any word character [a-zA-Z0-9_]. + Between one and unlimited times, as many times as possible, : will check for : literally
  • \s? : match any white space character [\r\n\t\f ]. ? Between zero and one time, as many times as possible
  • (\w+.\w+) : Capturing group of any word character [a-zA-Z0-9_]

So using preg_replace like as

echo preg_replace('/\[(\w+):\s?(\w+.\w+)]/',"<$1 src='$2' />","[img: something.jpg]");

Regex

Demo

Upvotes: 2

Related Questions