How do I "clean" a String in PHP using regex? - php

For example suppose I have
$blah = "C$###.a534&";
I wish to filter the string so that only letters, numbers and "." remain yielding "C.a534"
How do I do this?

If you know what characters should be allowed, you can use a negated character group (in a regular expression) to remove everything else:
$blah = preg_replace('/[^a-z0-9\.]/i', '', $blah);
Note that i am using the i modifier for the regular expression. It matches case-insensitive, so that we do not need to specify a-z and A-Z.

been answered lots of times but:
function cleanit($input){
return preg_replace('/[^a-zA-Z0-9.]/s', '', $input);
}
$blah = cleanit("C$###.a534&");

you can use preg_replace
$text = preg_replace('/[' . preg_quote('CHARSYOUDONTWANT','/') . ']/','',$text);
on other case for only chars you want try this,
$text = preg_replace('/[^' . preg_quote('CHARSONLYYOUWANT','/') . ']/','',$text);
for example
$blah = "C$###.a534&";
$blah = preg_replace('/[' . preg_quote('$##&','/') . ']/','',$blah);
echo $blah;

Or do it the other way round:
$text = preg_replace('/[^a-zA-Z0-9.]/','',$text);

http://php.net/manual/en/function.preg-replace.php
replace all non-valid characters with the empty string.

Related

How do I replace all uppercase letters with a dash and lowercase with regex?

How does one replace all uppercase letters with a dash and lowercase equivalent in php?
Such as understandRegexBetter to understand-regex-better?
My Google-fu and experimentation with the following code hasn't gotten me very far.
echo preg_replace('/[A-Z]+/', "-$'", "understandRegexBetter");
Edit:
I forgot to specifically state that the first character is never uppercase.
Preferred Method:
This method replaces any set of capital letters preceded by a lowercase letter with a - and the set of capital letters. Then we lowercase the whole string after the fact.
echo strtolower(preg_replace(
'/(?<=[a-z])([A-Z]+)/',
'-$1',
'understandRegexBetter'
));
RegEx Callback:
Uses preg_replace_callback() to replace any set of capital letters with a - followed by the letters passed through strtolower(). This, however, will leave a preceding - in your string (we could look for a preceding characters in the RegEx, but then your first letter would be left uppercase).
echo preg_replace_callback(
'/[A-Z]+/',
function ($matches) {
$character = reset($matches);
return '-' . strtolower($character);
},
'understandRegexBetter'
);
Deprecated:
Side note, you can technically use preg_replace() with the e modifier but it is deprecated as of PHP 5.5. An example would be:
echo preg_replace(
'/([A-Z]+)/e',
'"-" . strtolower("$1")',
'understandRegexBetter'
);
You can do this:
echo strtolower(preg_replace('~(?=[A-Z])(?!\A)~', '-', $str));
try this:
echo strtolower(preg_replace('/([A-Z]+)/', "-$1", "understandRegexBetter"));
You can use:
$s = 'understandRegexBetter';
$r = preg_replace_callback('~(?<=[a-z])([A-Z])~',
function ($m) { return '-' . strtolower($m[1]); }, $s);
echo $r;
You could try something like this (e flag means evaluate):
echo preg_replace('/([A-Z])/e', "strtolower('-\\1')", "understandRegexBetter");

How can I insert symbol '+' after each char of a string?

How can I insert symbol '+' after each char of a string?
Like changing from mystring to m+y+s+t+r+i+n+g+.
You can also use this:
print implode("+", str_split($string));
To add one extra + after, just concatenate . "+".
Note: this approach is fast enough for not very long strings. Another way is to use regular expressions as illustrated in #zerkms answer.
$str = 'string';
echo preg_replace('~.~', '\\0+', $str);
You can use preg_replace:
$text = 'mystring';
// To match only characters (no numbers):
$replaced = preg_replace("/([a-z])/i", "$1+", $text);
// To match both
$replaced = preg_replace("/([a-z0-9])/i", "$1+", $text);

Passing Charachter in to Regex in PHP

I would like to pass characters like A,B,C,D like this to a preg_match function in PHP.
Eg >
if (preg_match ("/^SEQRES.*\s$char\s.*/", $amino)) ;
I would like to pass A,B,C,D to $char and loop through the match.
please give me a solution.
Just use string concatenation:
$re = "/^SEQRES.*\s" . $char . "\s.*/";
if (preg_match($re, $amino))
....
There is no need for a loop. Simply replace $char with "[A-D]";. Since you have bounded it by spaces, it will match one single character in the class [A-D] between spaces .
if (preg_match ("/^SEQRES.*\s[A-D]\s.*/", $amino)) ;
You may also wish to use preg_match_all().
Use preg_quote if you are getting the character from user input:
$re = "/^SEQRES.*\s" . preg_quote($char) . "\s.*/";

RegEx to handle Alphanumeric Input - PHP

I have this code.
<?php
$USClass = "3/312";
$USClass = preg_replace_callback('~[\d.]+/[\d.]+~', function ($matches) {
$parts = explode('/', $matches[0]);
return $parts[1] . ',' . $parts[0];
}, $USClass);
echo $USClass;
?>
It prints 312,3 which is what I wanted.
However, if I give an input like D12/336 then it does not work. I want it to print 336,D12
How can I do it? and What is wrong with my current code which is not handling this Alphanumeric? Is it because I used \d ?
EDIT:
I want it to handle inputs like this as well
148/DIG.111
then the output should be DIG.111,148
Yes \d does only contain digits.
You can try \w instead this is alphanumeric, but additionally it includes also _
To be Unicode you can go for
~[\pL\d.]+/[\pL\d.]+~u
\pL is a Unicode code point with the property "Letter"
The u at the end turn on the UTF-8 mode that is needed to use this feature
See http://www.php.net/manual/en/regexp.reference.unicode.php
Other solution
I think you ar e doing this a bit complicated. It would be simplier if you would make use of capturing groups.
Try this:
$in = "148/DIG.111";
preg_match_all('~([\w.]+)/([\w.]+)~', $in, $matches);
echo $matches[2][0] . ',' . $matches[1][0];
Explanation:
([\w.]+)/([\w.]+)
^^^^^^^^ ^^^^^^^^
Group 1 Group 2
Because of the brackets the matched substring is stored in the array $matches.
See here for more details on preg_match_all
With a simple preg_replace:
$USClass = "148/DIG.111";
$USClass = preg_replace('#(.+?)/(.+)#', "$2,$1", $USClass);
echo $USClass;
output:
DIG.111,148

Remove unallowed character from specific pattern in the php

I have a text field in which user can enter any character he/she wants. But in server i have a string patter [a-z0-9][a-z0-9+.-]*, if any of the character in the value from the text box doesn't match the pattern, then i must remove that character from that string. How can i do that in php. is there any functions for that?
Thanks in advance.
Gowri Sankar
.. in PHP we use regular Expressions with preg_replace.
Here you have some help with examples...
http://www.addedbytes.com/cheat-sheets/regular-expressions-cheat-sheet/
this is what you need:
$new_text = preg_replace('#[^A-Za-z+.-0-9]#s','',$text);
Just use preg_replace with the allowed pattern negated.
For example, if you allow a to Z and spaces, you simply negate it by adding a ^ to the character class:
echo preg_replace('/[^a-z ]*/i', '', 'This is a String !!!');
The above would output: This is a String (without the exclamation marks).
So it's removing any character that is not a to Z or space, e.g. your pattern negated.
How about:
$string = 'A quick test &*(^&for you this should work';
$searchForThis = '/[^A-Za-z \s]/';
$replaceWithBlank = '';
echo preg_replace($searchForThis, $replaceWithBlank , $string);
Try this:
$strs = array('+abc123','+.+abc+123','abc&+123','#(&)');
foreach($strs as $str) {
$str = preg_replace('/(^[^a-z0-9]*)|([^a-z0-9+.-]*)/', '', $str);
echo "'",$str,"'\n";
}
Output:
'abc123'
'abc+123'
'abc+123'
''
str_replace('x','',$text);

Categories