I do not want to use stripslashes() because I only want to replace "\\" with "\".
I tried preg_replace("/\\\\/", "\\", '2\\sin(\\pi s)\\Gamma(s)\\zeta(s) = i\\oint_C \\frac{-x^{s-1}}{e^x -1} \\mathrm{d}x');
Which to my disapointment returns: 2\\sin(\\pi s)\\Gamma(s)\\zeta(s) = i\\oint_C \\frac{-x^{s-1}}{e^x -1} \\mathrm{d}x
Various online regex testers indicate that the above should work. Why is it not?
First, like many other people are stating, regular expressions might be too heavy of a tool for the job, the solution you are using should work however.
$newstr = preg_replace('/\\\\/', '\\', $mystr);
Will give you the expected result, note that preg_replace returns a new string and does not modify the existing one in-place which may be what you are getting hung up on.
You can also use the less expensive str_replace in this case:
$newstr = str_replace('\\\\', '\\', $mystr);
This approach costs much less CPU time and memory since it doesn't need to compile a regular expression for a simple task such as this.
You dont need to use regex for this, use
$newstr = str_replace("\\\\", "\\", $mystr);
See the str_replace docs
Related
It's been a couple years since I used RegEx, and being fairly novice even back then, I'm getting stumped on what I thought would be an easy one.
I have two data sources which I need to compare, and one has double-quotes " denoting inches while the other uses doubled-single-quotes ''.
As I'm iterating through, I need to convert the single-doubles " to double-singles ''.
I started off playing with preg_match(), and once I had a pattern returning TRUE, I moved it to preg_replace(). Looks like my feeble attempt is not holding up, though.
Let's take a look:
$str = 'PRE-301 1/8" ID 48" BX';
preg_replace( '/(\d+)\"/', "\1''", $str );
echo '<pre>',var_dump($str),'</pre>';
My goal is to get a string(24) "PRE-301 1/8'' ID 48'' BX". What I am getting, though, is just the original string(22) "PRE-301 1/8" ID 48" BX" back.
You are not assigning the value back, and you need to change \1 to $1 in your replacement.
$str = preg_replace('/(\d+)"/', "$1''", $str);
Live Demo
Note: You can remove the backslash before your quotes, it's not neccessary here. And if your strings are always like this, you can use just replace the quotes alone using str_replace():
$str = str_replace('"', "''", $str);
Couple of things here.
preg_replace doesn't change the string in place, but returns a value. So you are looking for:
$new_str = preg_replace(...
Double quote (and single for that matter) are not metacharacters in Regex, so you are free to leave off the \ in front of the ". It won't hurt anything, but it's a bit more readable, which is nice with Regex!
Instead of wondering what regex I need for each time I need a regex, I like to learn how to do basic string replacement with regexes.
How do you take one string and replace it with another with regexes in PHP ?
For example how do you take all '/' and replace them with '%' ?
If you just want to do basic string replacement (i.e. replace all 'abc' with '123') then you can use str_replace, which doesn't require using regex. For basic replacements, this will be easier to set up and should run faster.
If you want to use this as a tool to learn regex though (or need more complicated replacements) then preg_replace is the function you need.
You should look into preg_replace. For your question
$string = "some/with/lots/of/slashes";
$new_string = preg_replace("/\//","%",$string);
echo $new_string;
I like to learn how to do basic string replacement with regexes.
That's a little broad for this forum. However, to answer a more specific question like:
For example how do you take all '/' and replace them with '%' ?
You could do that like this:
$result = preg_replace('#\/#', '%', 'Here/is/a/test/string.');
Here is a Rubular that proves the regex.
Note, you are not limited to using the common / delimiter, which means when working with forward slashes it is often easier to change to a different delimiter EG.
$mystring = 'this/is/random';
$result = preg_replace('#/#', '%', $mystring);
This will make '#' the delimiter, rather than the standard '/', so it means you do not need to escape the slash.
I would do this simply with strtr which is very suitable for character mapping, e.g.
strtr('My string has / slashes /', '/', '%');
If you want to also replace the letter a with a dash:
strtr('My string has / slashes /', '/a', '%-');
As you can see, the second and third argument define the transformation map.
So I've seen a couple articles that go a little too deep, so I'm not sure what to remove from the regex statements they make.
I've basically got this
foo:bar all the way to anotherfoo:bar;seg98y34g.?sdebvw h segvu (anything goes really)
I need a PHP regex to remove EVERYTHING after the colon. the first part can be any length (but it never contains a colon. so in both cases above I'd end up with
foo and anotherfoo
after doing something like this horrendous example of psuedo-code
$string = 'foo:bar';
$newstring = regex_to_remove_everything_after_":"($string);
EDIT
after posting this, would an explode() work reliably enough? Something like
$pieces = explode(':', 'foo:bar')
$newstring = $pieces[0];
explode would do what you're asking for, but you can make it one step by using current.
$beforeColon = current(explode(':', $string));
I would not use a regex here (that involves some work behind the scenes for a relatively simple action), nor would I use strpos with substr (as that would, effectively, be traversing the string twice). Most importantly, this provides the person who reads the code with an immediate, "Ah, yes, that is what the author is trying to do!" instead of, "Wait, what is happening again?"
The only exception to that is if you happen to know that the string is excessively long: I would not explode a 1 Gb file. Instead:
$beforeColon = substr($string, 0, strpos($string,':'));
I also feel substr isn't quite as easy to read: in current(explode you can see the delimiter immediately with no extra function calls and there is only one incident of the variable (which makes it less prone to human errors). Basically I read current(explode as "I am taking the first incident of anything prior to this string" as opposed to substr, which is "I am getting a substring starting at the 0 position and continuing until this string."
Your explode solution does the trick. If you really want to use regexes for some reason, you could simply do this:
$newstring = preg_replace("/(.*?):(.*)/", "$1", $string);
A bit more succinct than other examples:
current(explode(':', $string));
You can use RegEx that m.buettner wrote, but his example returns everything BEFORE ':', if you want everything after ':' just use $2 instead of $1:
$newstring = preg_replace("/(.*?):(.*)/", "$2", $string);
You could use something like the following. demo: http://codepad.org/bUXKN4el
<?php
$s = 'anotherfoo:bar;seg98y34g.?sdebvw h segvu';
$result = array_shift(explode(':', $s));
echo $result;
?>
Why do you want to use a regex?
list($beforeColon) = explode(':', $string);
I have a string
$name = "name1?name2?name3?name4";
I want to modify this variable as
$name2 = "name1/name2/name3/name4";
using php preg_replace.
How can I do this?
You have to escape the ? with \
<?php
$string = 'name1?name2?';
$pattern = '/\?/';
$replacement = '/';
echo preg_replace($pattern, $replacement, $string);
?>
Time to test...
I stand by my answer, as it answered the OP's question most directly. But my speed comment was not accurate - at all. The differences I found are easy to see, but weren't that impressive IMO.*
The Benchmark: I took the OP's string and concatenated it 500000 times - so each function would have plenty of replacements to do (1.5- or 2-million depending).
Here are the functions and their speeds:
str_replace('?', '/', $test); // name1/name2/name3/name4/
0.388642073
0.389673948
0.385308981
preg_replace('/\?/', '/', $test); // name1/name2/name3/name4/
0.812348127
0.812065840
0.819634199
$bad = array('1?','2?','3?');
$good = array('1/','2/','3/');
str_replace($bad, $good, $test); // name1/name2/name3/name4?
0.712552071
0.725568056
0.718420029
preg_replace('/\?(\w+\d+)/', '/$1', $test); // name1/name2/name3/name4?
1.515372038
1.516302109
1.517566919
So...I lose. This testing showed str_replace() to be 2X faster than preg_replace(). But, 1.5 seconds vs 0.7 seconds (last two functions) isn't bad when you consider all 1.5 million replacements are finished - not to mention the last one will resolve many more combinations than its competitor.
Don't you want the celebratory fist-pump when you write that perfect RegEx function? :-)
You can easily do with str_replace. I don't think there is a need of preg family
$name2=str_replace("?","/",$name)
You can use str_replace, just like #Shakti said.
Or, if you insist on doing it with preg_replace, you can do like this:
$name2 = preg_replace("|\?|", "/", $name);
echo $name2;
The difference between str_replace and preg_replace is, preg_replace do replacement using regex. And, on regex, character ? has special meaning. In order to make it meaningless to preg_replace, you have to escape it using \.
For more information, go, read each function's description on PHP manual:
preg_replace
str_replace
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.