2

I am having an issue with string parsing in php. I am trying to create my own template parser (for my learning purpose). I have decided to put urls in the following format {url:abc/def} so this would be displayed like http://www.domain.com/abc/def. I have tried using str_replace but in this case it would not work since the value after ":" could be anything. Exploding the string also wont work as ":" can also be present in the text of html file. I think this could be only done via regular expression so suggest me some good regular expression also do let me know if this can be achieved via any other approach.

Other things to note.

  1. Since it is used for template parsing and template can have multiple urls.
  2. Urls would not have any query strings but i would appreciate if the solution also supports them.
3
  • If the contents could be "anything", it's not regular and not a good use for regular expressions. What you want is a proper parser. Look at github.com/fabpot/Twig for a decent templating language with a decent parser. I'd even suggest you use and extend Twig to your needs instead of reinventing the wheel. Commented Aug 26, 2013 at 8:02
  • i have mention that i am building it for my learning purpose. I know there are good templating engines like smarty and others. Also the url value could be anything but the pattern remains the same so i think this could be achieved using regular expression. Commented Aug 26, 2013 at 8:07
  • preg_replace_callback() is your friend. Commented Aug 26, 2013 at 8:23

1 Answer 1

4

for learning purposes then:

preg_replace('/\{url:([^\}]*)\}/', $base_url.'$1', $string);

And the explanation of the regex

  1. \{url: <-- find this text
  2. [^\}]* <-- this means 'any character but a } occuring 0 or more times
  3. ([^\}]*) <-- by putting it inbetween () we can later reference it (see the '$1')
  4. \} <-- the closing }

As long as you're learning: take a look at http://www.regular-expressions.info/ for more info on regular expressions. They're quite awesome really :D

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

1 Comment

Thanks. Work like a charm :)

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.