Can anyone give me a quick summary of the differences please?
To my mind, are they both doing the same thing?
str_replace replaces a specific occurrence of a string, for instance "foo" will only match and replace that: "foo". preg_replace will do regular expression matching, for instance "/f.{2}/" will match and replace "foo", but also "fey", "fir", "fox", "f12", etc.
[EDIT]
See for yourself:
$string = "foo fighters";
$str_replace = str_replace('foo','bar',$string);
$preg_replace = preg_replace('/f.{2}/','bar',$string);
echo 'str_replace: ' . $str_replace . ', preg_replace: ' . $preg_replace;
The output is:
str_replace: bar fighters, preg_replace: bar barhters
:)
str_replace will just replace a fixed string with another fixed string, and it will be much faster.
The regular expression functions allow you to search for and replace with a non-fixed pattern called a regular expression. There are many "flavors" of regular expression which are mostly similar but have certain details differ; the one we are talking about here is Perl Compatible Regular Expressions (PCRE).
If they look the same to you, then you should use str_replace.
str_replace searches for pure text occurences while preg_replace for patterns.
I have not tested by myself, but probably worth of testing. But according to some sources preg_replace is 2x faster on PHP 7 and above.
See more here: preg_replace vs string_replace.
Related
I am trying to write some string replace functions, and rather than ask how to do a specific replace, I want to know more about modifiers so I can do it myself
Take this for example:
preg_replace('~[\W\s]~', ' ', $input);
or
strlen(preg_replace('![^A-Z]+!', '', $s));
What are those called? (~[\W\s]~) (![^A-Z]+!)
They make very little sense to read or make up a new one. Where can I find all of them? Or learn how to write them?
They are called Regular Expressions. From http://www.regular-expressions.info , 'A regular expression (regex or regexp for short) is a special text string for describing a search pattern. You can think of regular expressions as wildcards on steroids.'
Here is a site with references and a playground to test working with them.
http://regexr.com
I've been looking all over the internet for some useful information and I think I found too much. I'm trying to understand regular expressions but don't get it.
Lets for instance say $data="A bunch of text [link=123] another bunch of text.", and it should get replaced with "< a href=\"123.html\">123< /a>".
I've been trying around a lot with code similar to this:
$find = "/[link=[([0-9])]/";
$replace = "< a href=\"$1\">$1< /a>";
echo preg_replace ($find, $replace, $data);
but the output is always the same as the original $data.
I think I have to see something relevent to my problem understand the basics.
Remove the extra [] around the (), and add + after the [0-9] to quantify it. Also, escape the [] that make up the tag itself.
$find = "/\[link=(\d+)\]/"; // "\d" is equivalent to "[0-9]"
$replace = "$1";
echo preg_replace($find,$replace,$data);
The regex would be \[link=([\d]+)\]
A good source for an quick overview of regular expression can you find here http://www.regular-expressions.info/
When you really interested in the power of regular expression, you should buy this book: Mastering Regular Expressions
A good Programm to test your RexEx on a Windows Client is: RegEx-Trainer
You are missing the + quantifier and as a result of this your pattern matches if there is a single digit following link=.
And there is an extra pair of [..] as a result of this the outer [...] will be treated as the character class.
You also forgot the escape the closing ].
Solution:
$find = "/[link=([0-9]+)\]/";
<?php
$data= "A bunch of text [link=123] another bunch of text.";
$find = '/\[link=([0-9]+?)\]/';
echo preg_replace($find, "$1", $data);
I'm new to preg_replace() and I've been trying to get this to work, I couldn't so StackOverflow is my last chance.
I have a string with a few of these:
('pm_IDHERE', 'NameHere');">
I want it to be replaced with nothing, so it would require 2 wildcards for NameHere and pm_IDHERE.
But I've tried it and failed myself, so could someone give me the right code please, and thanks :)
Update:
You are almost there, you just have to make the replacement an empty string and escape the parenthesis properly, otherwise they will be treated as capture group (which you don't need btw):
$str = preg_replace("#\('pm_.+?', '.*?'\);#si", "", $str);
You probably also don't need the modifiers s and i but that is up to you.
Old answer:
Probably str_replace() is sufficient:
$str = "Some string that contains pm_IDHERE and NameHere";
$str = str_replace(array('pm_IDHERE', 'NameHere'), '', $str);
If this is not what you mean and pm_IDHERE is actually something like pm_1564 then yes, you probably need regular expressions for that. But if NameHere has no actual pattern or structure, you cannot replace it with regular expression.
And you definitely have to explain better what kind of string you have and what kind of string you have want to replace.
This is my first question on this wonderful website.
Lets say I have a string $a="some text..%PROD% more text" There will be just one %..% in the string. I need to replace PROD between the % with another variable content. So I used to do:
$a = str_replace('%PROD%',$var,$a);
but now the PROD between % started coming in different cases. So I could expect prod or Prod. So I made the entire string uppercase before doing replacement. But the side effect is that other letters in the original string also became uppercase. Someone suggested me to use regular expression. But how ?
Thanks,
Rohan
You can make use of str_ireplace function. Its similar to str_replace but is case insensitive during matching.
$x = 'xxx';
$str = 'abc %Prod% def';
$str = str_ireplace('%PROD%',$x,$str); // $str is now "abc xxx def"
Just use str_ireplace(). It's a case-insensitive version of str_replace(), and much more efficient for a simple replacement than regular expressions (also much more straightforward).
You could use a regular expression, but PHP also conveniently has a case-insensitive version of str_replace, str_ireplace
I'm trying to remove some deprecated code from a site.
Can anyone tell me the preg equivalent of
ereg_replace("<b>","<strong>",$content);
Thanks.
There seems to be no need for regular expressions at all.
a simple str_replace would do:
$cleaned = str_replace ('<b>', '<strong>', $unCleaned);
If you need more complicated replacements, for example checking the attributes, you could do:
$cleaned = preg_replace('/<b(\s[^>]*)?>/', '<strong\\1>', $unCleaned);
But this is by no means perfect; something like <div title="foo->bar"></div> would break the regular expression.
A PCRE equivalent to your ERE regular expression would be:
preg_match("/<b>/", "<strong>", $content)
But as Jacco already noted you don’t need a regular expression at all as you want to replace a constant value.