How to add slash to a special character in PHP? - php

I am trying to add a back slash to a string having special character.
My input is:
db:xz~sf!fkd#djf#dfs$dlf%dks^kd&fkf*kdf(dls)kls-fls+fsd=slf_fls[fdf]fdf{ffl}sl|dkf\fsl'skfj
And my output should be:
db\:xz\~sf\!fkd\#djf\#dfs\$dlf\%dks\^kd\&fkf\*kdf\(dls\)kls\-fls\+fsd\=slf\_fls\[fdf\]fdf\{ffl\}sl\|dkf\\fsl\'skfj
And I have the following piece of code which is only replacing the special character with the back slash character:
<?php
echo $string = "db:xz~sf!fkd#djf#dfs$dlf%dks^kd&fkf*kdf(dls)kls-fls+fsd=slf_fls[fdf]fdf{ffl}sl|dkf\fsl'skfj";
echo preg_replace('/[^A-Za-z0-9\-]/', '\\', $string);
So could someone help me regarding this?

You can use:
$s = 'db:xz~sf!fkd#djf#dfs$dlf%dks^kd&fkf*kdf(dls)kls-fls+fsd=slf_fls[fdf]fdf{ffl}sl|dkf\fsl\'skfj';
echo preg_replace('/\W/', '\\\\$0', $s)
//=> db\:xz\~sf\!fkd\#djf\#dfs\$dlf\%dks\^kd\&fkf\*kdf\(dls\)kls\-fls\+fsd\=slf_fls\[fdf\]fdf\{ffl\}sl\|dkf\\fsl\'skfj

Related

PHP preg_replace odd characters not working

I have the following code, but for some reason, the characters are not replaced....
test.php
<?php
$s = 'AABBCC����ˮ��������Ƽ���� �˾XXYYZZ';
$softwareVersion = preg_replace('[^a-zA-Z\d\s\.]', '', $s);
echo $softwareVersion . "\n";
what I am getting
jeffreylroberts:~$ php test.php
AABBCC����ˮ��������Ƽ���� �˾XXYYZZ
jeffreylroberts:~$
what I am expecting
jeffreylroberts:~$ php test.php
AABBCC XXYYZZ
jeffreylroberts:~$
Any ideas on how to preg_replace those characters?
You forgot to add a leading an trailing forward slash in the regex, This will give you the output you need:
$softwareVersion = preg_replace('/[^a-zA-Z0-9\d\s\.]/', '', $s);
Also you can do it this way, which will remove all characters except alphanumeric and underscore:
$softwareVersion = preg_replace('/\W/', '', $s);
A few things to tweak:
Use a pattern delimiter. / is the most common one.
Reduce your pattern length by only writing a-z in the character class and use the i modifier/flag at the end of your pattern.
Escaping the dot is not necessary in the character class.
Use the + "one or more" quantifier to improve efficiency. It will match consecutive occurrences of character and replace the multi-character substring in one shot.
Code: (Demo)
$s='AABBCC����ˮ��������Ƽ���� �˾XXYYZZ';
$softwareVersion = preg_replace('/[^a-z\d\s.]+/i','',$s);
echo $softwareVersion . "\n";
Output:
AABBCC XXYYZZ

How to replace backslashes with forward slashes without changing the content of the link

There is an old question from 2011 but with a wrong answer.
Maybe now someone can give a better answer. The question was: How can we replace the backslashes with forward slashes from this variable-link:
$str = "http://www.domain.com/data/images\flags/en.gif";
The wrong answer was that:
echo $str = str_replace('\\', '/', $str);
And it was wrong because the result of that code changes the content of the link. (http://www.domain.com/data/imageslags/en.gif)
It finds not only the backslash but the letter f after that and it deletes them because \f means "formfeed (hex 0C)". So how can we avoid this wrong replacement?
The Code is here
i hope this helps you
$str = "http://www.domain.com/data/images\flags/en.gif";
echo $str = str_replace('lags', "/flags", $str);
You can use addcslashes but you'll have to specify each possible escaped character that could occur in $str
$str = "http://www.domain.com/data/images\flags/en.gif";
$escaped = str_replace("\\","/",addcslashes($str,"\f\r\n\t"));
echo $escaped; // result is 'http://www.domain.com/data/images/flags/en.gif'

preg_replace vs trim PHP

I am working with a slug function and I dont fully understand some of it and was looking for some help on explaining.
My first question is about this line in my slug function $string = preg_replace('# +#', '-', $string); Now I understand that this replaces all spaces with a '-'. What I don't understand is what the + sign is in there for which comes after the white space in between the #.
Which leads to my next problem. I want a trim function that will get rid of spaces but only the spaces after they enter the value. For example someone accidentally entered "Arizona " with two spaces after the a and it destroyed the pages linked to Arizona.
So after all my rambling I basically want to figure out how I can use a trim to get rid of accidental spaces but still have the preg_replace insert '-' in between words.
ex.. "Sun City West " = "sun-city-west"
This is my full slug function-
function getSlug($string){
if(isset($string) && $string <> ""){
$string = strtolower($string);
//var_dump($string); echo "<br>";
$string = preg_replace('#[^\w ]+#', '', $string);
//var_dump($string); echo "<br>";
$string = preg_replace('# +#', '-', $string);
}
return $string;
}
You can try this:
function getSlug($string) {
return preg_replace('#\s+#', '-', trim($string));
}
It first trims extra spaces at the beginning and end of the string, and then replaces all the other with the - character.
Here your regex is:
#\s+#
which is:
# = regex delimiter
\s = any space character
+ = match the previous character or group one or more times
# = regex delimiter again
so the regex here means: "match any sequence of one or more whitespace character"
The + means at least one of the preceding character, so it matches one or more spaces. The # signs are one of the ways of marking the start and end of a regular expression's pattern block.
For a trim function, PHP handily provides trim() which removes all leading and trailing whitespace.

How to Remove Space Additionally to the Special Chars?

in my functions.php if have this code:
echo ''.urldecode($search).'';
this removes the special chars..
but how can i additonally add remove space and replace it with - and remove "
so, if someone types in "yo! here" i want yo-here
Try:
<?php
$str = '"yo! here"';
$str = preg_replace( array('/[^\s\w]/','/\s/'),array('','-'),$str);
var_dump($str); // prints yo-here
?>
If you want to replace a run of unwanted characters with a single dash, then you can use something like this:
preg_replace('/\W+/', '-', $search);
To remove surrounding quotes, and then replace any other junk with dashes, try this:
$no_quotes = preg_replace('/^"|"$/', '', $search);
$no_junk = preg_replace('/\W+/', '-', $no_quotes);
This will replace multiple spaces / "special" chars with a single hyphen. If you don't want that, remove the "+".
You might want to trim off any trailing hyphens, should something end with an exclamation point / other.
<?php
preg_replace("/\W+/", "-", "yo! here check this out");
?>
You can remove any non-words:
preg_replace('/\W/', '-', $search);

REGEX (in PHP).. remove non-alphanumeric characters at ends?

$test = "!!! sdfsdf sd$$$fdf ___";
$test = str_replace(' ', '_', $test); // Turn all spaces into underscores.
echo $test."<br />"; // Output: !!!___sdfsdf___sd$$$fdf______
$test = preg_replace('/[^a-zA-Z0-9_-]/', '-', $test); // Replace anything that isn't alphanumeric, or _-, with a hyphen.
echo $test."<br />"; // Output: !!!___sdfsdf___sd---fdf______
$test = preg_replace('/([_-])\1+/', '$1', $test); // Reduce multiple _- in a row to just one.
echo $test."<br />"; // Output: !_sdfsdf_sd-fdf_
The above code is what I currently have, what I'm trying to figure out the REGEX for is how to cut off any non-alphanumeric characters off the ends. So turning the final output from "!_sdfsdf_sd-fdf_" to "sdfsdf_sd-fdf".
$clean = preg_replace('~(^[^a-z0-9]+)|([^a-z0-9]+$)~i', '', $str);
You can use trim():
$test = trim($test, '_-');
echo $test;
The "!" won't make it past the first regular expression.
You can replace your whole code with this:
$test = preg_replace('/[^a-zA-Z0-9]+/', '_', $test);
$test = trim($test, '_');
The first will replace all occurrences of one or more illegal characters with _ and the second will rmove any remaining _ from the start and end.
[a-zA-Z0-9].*[a-zA-Z0-9]
Meaning: Read any alphanumeric character, then read as much of anything as we can, making sure we can get at least one alphanumeric character at the end.

Categories