PHP preg_replace/preg_match vs PHP str_replace
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
:)
preg_replace and str_replace, can't seem to use together
As I said in comments, you're replacing the tag with blocks as well, before passing it to the regular expression match. Something like this should do the trick. preg_replace_callback()
works almost the same as preg_replace()
but you get to use a function to say what you're replacing the string with.
<?php
$string = "Here is a secret: [secret]foo bar baz[/secret]";
$result = preg_replace_callback("/\[secret\](.*?)\[\/secret\]/si", function($matches) {
return preg_replace("/[\w ]/i", "█", $matches[1]);
}, $string);
echo $result;
You can see the problem with your original code if you break it down to multiple steps:
<?php
$replace = array(" ", "a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z", "A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z");
$redacted = str_replace($replace, "█", $text);
// Clearly, the string "secret" is gone by now, so the regex will never match
$text = preg_replace('#\[secret\](.*?)\[/secret\]#si', '\1', $redacted);
PHP str_replace or preg_match or strpos when specific string plus if integer
preg_replace()
is the appropriate function for this.
$str = preg_replace('/-\d+x\d+\.jpg$/', '.jpg', $str);
preg_replace or str_replace don't work
Try this:
$var = preg_replace("/\"/", "\\\"", $test);
php: preg_match and preg_replace
$string = "Hello, isn't the /bo weather just /it beautiful /bo today!?";
var_dump(preg_replace (array('/\/bo\s(\w+)/', '/\/it\s(\w+)/'), array('<b>$1</b>', '<i>$1</i>'), $string));
"Hello, isn't the weather just beautiful today!?"
Are preg_match() and preg_replace() slow?
As Mike Brant said in his answer: There's nothing wrong with using any of the preg_*
functions, if you need them.
You want to know if it's a good idea to have something like 20 preg_match
calls in a single file, well, honestly: I'd say that's too many. I've often stated that "if your solution to a problem relies on more than 3 regex's at any given time, you're part of the problem". I have occasionally sinned against my own mantra, though.
If you are using 20 preg_match
calls, chances are you can halve that number simply by having a closer look at the actual regular expressions. Regex's, especially the Perl regex, are incredibly powerful, and are well worth the time to get to know them. The reason why they tend to be slower is simply because the regex has to be parsed, and "translated" to a considerable number of branches and loops at some low level. If, say, you want to replace all lower-case a
's with an upper-case char, you could use a regular expression, sure, but in PHP this would look like this:
preg_replace('/a/','A',$string);
Look at the expression, the first argument: it's a string that is passed as an argument. This string will be parsed (when parsing, the delimiters are checked, a match string is created and then the string is iterated, each char is compared to the pattern (in this case a
), and if the substring matches, it's replaced.
Seems like a bit of a hasstle, especially considering that the last step (comparing substrings and replace matches) is all we really want.
$string = str_replace('a','A',$string);
Does just that, without the additional checks performed when a regular expression is parsed and validated.
Don't forget that preg_match
also constructs an array of matches, and constructing an array isn't free either.
In short: regex's are slower because the expression is parsed, validated and finally translated into a set of simple, low-level instructions.
Note that, in some cases people use explode
and implode
for string manipulations. This, too, creates an array which is -again- not free. Considering that you're imploding that very same array shortly thereafter. Perhaps another option is more desirable (and in some cases preg_replace
can be faster here).
Basically: regex's need additional processing, that simple string functions don't require. But when in doubt, there's only 1 way to be absolutely sure: set up a test script...
Preg_replace/str_replace() for changing `` and `` instances to `` and `` respectively
<?php echo htmlspecialchars_decode($project['description']); ?>
Should get you what you need.
If you are ONLY looking to decode those, though, then:
<?php echo str_replace("<","<",str_replace(">",">",$project['description'])); ?>
And preg_replace should look like this:
<?php echo preg_replace(<,"<",preg_replace(>,">",$project['description'])); ?>
I'm pretty sure the &
isn't a special character, but if it does cause you issues, put a \
before it.
preg_match works but preg_replace does not
Have you tried?
$yourVar = preg_replace(["/\(from\s*\)/", "/\(\s*see\s*\)/"], "", $description);
According to documentation preg_replace does not work by reference.
Related Topics
How to Send JSON Response in Symfony2 Controller
Migrating Pure PHP Project to Yii Framework
How to Integrate Moneybookers in Web Application in PHP
Get Current Date, Given a Timezone in PHP
Using Regular Expressions to Extract the First Image Source from HTML Codes
How to Get PHPunit Mockobjects to Return Different Values Based on a Parameter
What Are the Differences of System(), Exec() and Shell_Exec() in PHP
Why Does "Echo '2' . Print(2) + 3" Print 521
Create Preg_Match for Password Validation Allowing (!@#$%)
How to Add Additional PHP Versions to Mamp
How to Save Dompdf Generated Content to File