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
$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>
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.
Find all the tags:
preg_match_all('/(%s[^%]%s)/', $input, $matches);
Get your replacements. This is dependent on your code, but basically just loops through $matches
.
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.