0

I know it's easy for the most of the people, but it isn't for me, regular expressions pain me alot.

What I need is to replace all the string inside the '%s' ... '%s' for a element:

original: I have read and accept %sthe terms of booking%s

what i want is to replace all the '%sthe terms of booking%s' for something like:

<a href="..." id="enlaceCondiciones" target="_blank" >Condiciones de venta</a>

Thanks in advance.

PD: Text inside the '%s' - '%s' changes depending on the user language, so a simple str_replace is not a solution in this case

3
  • str_replace is quite enough for the task as given. Commented Dec 9, 2013 at 17:44
  • no its not, because the text inside the '%s' are not always the same, it changes depending on the language that the user uses Commented Dec 9, 2013 at 17:48
  • 'the task as given' is key here. If you have multiple expression (and/or don't know all of them), use preg_replace('/%s[^%]+%s/', 'string_to_replace', $your_string). Commented Dec 9, 2013 at 17:50

2 Answers 2

1
$output = preg_replace("/%s(.+)%s/", "<a href="..." id="enlaceCondiciones" target="_blank" >$1</a>", '%sthe terms of booking%s');

$output:

<a href="..." id="enlaceCondiciones" target="_blank" >the terms of booking</a>
Sign up to request clarification or add additional context in comments.

Comments

0

I assume you're hacking together a basic templating system and want to replace all of the %s...%s tags in a string without necessarily knowing which are present. You'd need to do this in 3 steps.

  1. Find all the tags:

    preg_match_all('/(%s[^%]%s)/', $input, $matches);
    
  2. Get your replacements. This is dependent on your code, but basically just loops through $matches.

  3. Replace the tags, you can do this in one batch by loading your searches and replacements into arrays:

    str_replace(array('%sone%s','%stwo%s'), array('uno', 'dos'), $input);
    

As a note, you should always try to use the basic string functions when possible. Regular expressions incur overhead in processing and memory use that are unnecessary when doing simple operations.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.