1

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';
2
  • echo preg_replace("/\[img:\s*([^\]]+)\]/i","<img src='$1'>",$string) Commented Nov 21, 2015 at 5:10
  • eval.in/473133 Commented Nov 21, 2015 at 5:26

2 Answers 2

2

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

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

1 Comment

But OP didn't defined any of those scenarios @Starkeen. If OP identify any of these scenario I'll update as per required.
2

@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]');

1 Comment

That dot is an any character rather than a literal dot.

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.