How would you use a wildcard in a str_replace if this is possible? I am basically looking for some text, and replacing it. But the text may also contain som numbers on the end which i will need to replace as well.... Something might look like the following: str_replace('stringtofind% ', 'REPLACE WITH THIS' 'Searching in this'); Any ideas?
Ah, well, in that case you can do one of two things:- 1. [easy way out] use php string functions. 2. [hard way but well worth it in the long run] learn regular expressions from this tutorial. Cheers; -- Yoink
As far as I now str_replace does not have wildcards. $string = 'This is old text.'; $string = str_replace('old text', 'new text', $string); $string = 'This is old text.'; $string = preg_replace('/old text/', 'new text', $string); (the slashes are telling the regex matching system to start and end) Both of those do the same thing. str_replace is always better to use for a straight replace because it uses less resources. When you get into wildcard situations you have no choice but to use regular expressions, so in your case I would do this... $string = 'This is old text123 stuff'; $string = preg_replace('/old text.*? /', 'new text321 ', $string); This changes 'This is old text123 stuff' to 'This is new text321 stuff'. The .* is saying any type of character, the ? after it is saying stop at the next match after the ?. In this case the next match is a space but it could be a word or any other type of match. Without the ? it would replace everything after the text your looking for. regular expressions is well worth learning so in the previous post I would go through that regular expression tutorial when you have time.
Regular expressions might require a steeper learning curve but they are really worth it in the end. So powerful...
I do agree, however, I've found that I need it fairly rarely only. Still, it's a handy thing, on one rare occasion it has saved me a lot of very tricky coding.
Google "how to use regular expressions in php" or "how to use regex in php". It might take you an hour to get your head around it, but it will be worth it.