php preg_replace question mark ("?") - not working - php

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

Related

Preg Replace with Spaces but only single space

Okay so consider the following string:
"Hello How are you??"
I'd like it to return:
"Hello_How_are_you"
But my preg_replace is this:
preg_replace("/[^A-Za-z0-9]/","_",$string);
Which returns the following:
"Hello____How are you"
Whilst good, it gets rid of the foreign characaters but leaves a long line of ___ which looks ugly. I understand why, because it is replacing the spaces with _ which I what I asked it to do. However i'd like to to only output the one _ where it's replaced things.
How can I achiieve this, is it done in the regex or some other way?
Just add a quantifier: +. + means at least one of what was before, grab as many possible:
preg_replace("/[^A-Za-z0-9]+/","_",$string);
This can be an alternative regex.
$str = "Hello How are you??";
$op = preg_replace("/\s+/", "_", $str); // suggested by #Toto
//(or)
$op = preg_replace("/[\s]{1,}/", "_", $str);

php regex replace double backslash with single

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

PHP Regex to remove everything after a character

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);

Replace from one custom string to another custom string

How can I replace a string starting with 'a' and ending with 'z'?
basically I want to be able to do the same thing as str_replace but be indifferent to the values in between two strings in a 'haystack'.
Is there a built in function for this? If not, how would i go about efficiently making a function that accomplishes it?
That can be done with Regular Expression (RegEx for short).
Here is a simple example:
$string = 'coolAfrackZInLife';
$replacement = 'Stuff';
$result = preg_replace('/A.*Z/', $replacement, $string);
echo $result;
The above example will return coolStuffInLife
A little explanation on the givven RegEx /A.*Z/:
- The slashes indicate the beginning and end of the Regex;
- A and Z are the start and end characters between which you need to replace;
- . matches any single charecter
- * Zero or more of the given character (in our case - all of them)
- You can optionally want to use + instead of * which will match only if there is something in between
Take a look at Rubular.com for a simple way to test your RegExs. It also provides short RegEx reference
$string = "I really want to replace aFGHJKz with booo";
$new_string = preg_replace('/a[a-zA-z]+z/', 'boo', $string);
echo $new_string;
Be wary of the regex, are you wanting to find the first z or last z? Is it only letters that can be between? Alphanumeric? There are various scenarios you'd need to explain before I could expand on the regex.
use preg_replace so you can use regex patterns.

using preg_match to strip specified underscore in php

There has always been a confusion with preg_match in php.
I have a string like this:
apsd_01_03s_somedescription
apsd_02_04_somedescription
Can I use preg_match to strip off anything from 3rd underscore including the 3rd underscore.
thanks.
Try this:
preg_replace('/^([^_]*_[^_]*_[^_]*).*/', '$1', $str)
This will take only the first three sequences that are separated by _. So everything from the third _ on will be removed.
if you want to strip the "_somedescription" part: preg_replace('/([^]*)([^]*)([^]*)(.*)/', '$1_$2_$3', $str);
I agree with Gumbo's answer, however, instead of using regular expressions, you can use PHP's array functions:
$s = "apsd_01_03s_somedescription";
$parts = explode("_", $s);
echo implode("_", array_slice($parts, 0, 3));
// apsd_01_03s
This method appears to execute similarly in speed, compared to a regular expression solution.
If the third underscore is the last one, you can do this:
preg_replace('/^(.+)_.+?)$/', $1, $str);

Categories