replacing a string with preg_replace - php

I have a URL like this:
http://Example.com/mobile-ds-cams/mobile-gg-cams/ddd-webcams
Example:
$pattern = '/http://Example.com/(\w+)/(\w+)/(\w+)/i';
$replacement="http://Example.com/$2/$3";
$appUrl= preg_replace($pattern, $replacement, $appUrl);
What I want to achieve is this
http://Example.com/mobile-gg-cams/ddd-webcams
I am trying to keep 2 "sub-URLs" instead of 3. but it doesn't work..why?

You need to escape your forward-slashes within the pattern, or use different pattern delimiters.
$pattern = '/http:\/\/Example\.com\/(\w+)\/(\w+)\/(\w+)/i';
$pattern = '#http://Example\.com/(\w+)/(\w+)/(\w+)#i';

It doesn't work correctly because your expression contains characters with special meaning in a regex that have not been properly quoted.
To be 100% certain, use preg_quote like this:
$url = 'http://Example.com/'
$pattern = preg_quote($url.'{word}/{word}/{word}', '/');
$pattern = str_replace($pattern, '{word}', '(\w+)');
$pattern = "/$pattern/i";
$replacement = $url.'$2/$3';
$appUrl= preg_replace($pattern, $replacement, $appUrl);
Otherwise, it's simply too easy to get things wrong. For example, all of the other answers currently posted here get it wrong because they do not properly escape the . in Example.com. You can test this yourself if you feed them a string like e.g. http://Example!com, where ! can be any character you like.
Additionally, you are using strings such as $2 inside a double-quoted string literal, which is not a good idea in PHP because IMHO it's easy to get carried away. Better make that singly quoted and be safe.

Escape the slashes like this:
$pattern = '/http:\/\/Example.com\/(\w+)\/(\w+)\/(\w+)/i';
$replacement="http://Example.com/$2/$3";
$appUrl= preg_replace($pattern, $replacement, $appUrl);

Related

How to stop preg_replace() returning numerical references?

I'm using preg_replace() to perform a regular expression search and replace.
$string = "This isn't my real string but it is a good example.";
$result = preg_replace($pattern, $replacement, $string);
echo $result; // This isn’t my real string but it is a good example.
As you can see, $string contains a single quote. Regardless of whether a match is found, when I output the return value of preg_replace(), my single quote becomes ’
How can I stop preg_replace() returning numerical references such as ’? I need my string to keep the single quote character.
Update
Here's my pattern:
$pattern = '/#(\w+)/';
Update 2
Here's my replacement string:
$replacement = '#$1';
you can try using html_entity_decode() to achieve that
here is a snippet
$string = "This isn't my real string but it is a good example.";
$result = preg_replace($pattern, $replacement, $string);
echo html_entity_decode($result); // This isn't my real string but it is a good example.

Replace multiple items in a string

i've scraped a html string from a website. In this string it contains multiple strings like color:#0269D2. How can i make str_replace code which replace this string with another color ?
For instance something like this just looping through all color:#0269D in the fulltext string variable?
str_replace("color:#0269D","color:#000000",$fulltext);
you pass array to str_replace function , no need to use loop
$a= array("color:#0269D","color:#000000");
$str= str_replace($a,"", $string);
You have the right syntax. I would add a check:
$newText = str_replace("color:#0269D", "color:#000000", $fulltext, $count);
if($count){
echo "Replaced $count occurrences of 'color'.";
}
This code might be too greedy for what you're looking to do. Careful. Also if the string differs at all, for example color: #0269D, this replacement will not happen.
’str_replace’ already replaces all occurrences of the search string with the replacement string.
If you want to replace all colors but aren't sure which hexcodes you'll find you could use preg_replace to match multiple occurrences of a pattern with a regular expression and replace it.
In your case:
$str = "String with loads of color:#000000";
$pattern = '/color ?: ?#[0-9a-f]{3,6}/i';
$replacement = "color:#FFFFFF";
$result = preg_replace($pattern, $replacement, $str);

Regex to add quotation marks to an unquoted expression

I'm trying to build a regex that will use preg_replace to quote the right side of an expression if it's unquoted.
So myvar = 3 becomes myvar = '3'. It should only deal with unquoted strings that are contiguous (so if there any spaces on the first string need be quoted e.g. myvar = 3 5 will become myvar = '3' 5).
I also want it to ignore any quoted string, so myvar = 'this is quoted' should not be modified.
So far I have the code below:
$str = 'myvar = 3';
$regex = '/([\w\#\-]+) *(\=|\>|\>\=|\<|\<\=) *([\w]+)/i';
$replace = '\1 \2 \'\3\'';
$result = preg_replace($regex, $replace_str, $str);
What do I need to put in $regex to make this work?
You could use preg_replace_callback, or maybe this could work (right side of the regex only):
#([^\'\"])(\w+)([^\'\"])#
And replace like this:
$exp = '#([^\'\"])(\w+)([^\'\"])#';
$str = 'This is unquoted';
$quoted = preg_replace($exp, '\'$1$2$3\'', $str); // should hopefully be 'This is unquoted' after. Not tested.
It's kind of a hacky work-around though.
EDIT:
Yeah, no-go. I'd recommend preg_replace_callback then.
I eventually settled for the following:
$str = 'myvar = 3';
$regex = '/([\w\#\-]+) *(\=|\>|\>\=|\<|\<\=) *([^\s\']+)/i';
$replace = '\1 \2 \'\3\'';
$result = preg_replace($regex, $replace_str, $str);
I needed this as one step of a multi-step operation so I wanted to use this regex in question to bake an uber regex that would do everything in one go. However, it turns out preg_replace can also be fed 'search' and 'replace' arrays, so I went with that for my final solution. It's much easier to grasp that way as well.
Cheers.

Passing a pattern value from user to preg_match

Hello i have this code but there is a problem with preg_match on passing $pattern variable.
$pattern = htmlspecialchars($_POST['pregmatch']);
$pattern = "'".$pattern."'";
preg_match($pattern, $content, $m);
if i give this /<span class=\"product_title\">(.*)<\/span>/
in the $_POST['pregmatch'] pregmatch returns NULL.
If i change the code to this
//$pattern = htmlspecialchars($_POST['pregmatch']);
//$pattern = "'".$pattern."'";
preg_match('/<span class=\"product_title\">(.*)<\/span>/', $content, $m);
works like a charm.
So whats the deal here? Slashes creates this problem?
Thanks in advance.
Both of your additional lines appear to be causing a problem... if you were to do:
preg_match($_POST['pregmatch'], $content, $m);
You would probably get the desired result.
htmlspecialchars converts the angle brackets < and > from your input into the HTML escapes < and >. Thus your pattern becomes:
/<span class=\"product_title">(.*)<\/span>/
Which won't match the $content if that's still raw HTML.
Also adding ' around the pattern will screw it up:
$pattern = "'".$pattern."'";
You then had two delimiters.
'/<span class="product_title">(.*)<\/span>/'
Best idea is to use var_dump when unsure about variable state. And enable error_reporting whenever something doesn't work.

How to define pattern in preg_replace to remove spaces?

I have a string like this.
$string="howto old_iccid = 01920930123 new_iccid =102930123"
How to remove space character in order to get string like this:
$string="howto old_iccid=01920930123 new_iccid=102930123"
I have used preg_replace, but still not understand to define the pattern which is handling those things..
How to define pattern in preg_replace to remove spaces?
$string = "howto old_iccid = 01920930123 new_iccid =102930123";
$string = preg_replace('/\s*=\s*/', '=', $string);
var_dump($string);

Categories