Remove unallowed character from specific pattern in the php - 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);

Related

How to allow all kinds of letters from all alphabets in preg_replace with php?

The issue:
Basically when it sees type of letter that regex don't allow it messes up with the link.
My function in php to convert the names that are read from database into links:
function convertActor($str) {
$regex = "/([a-zA-Z-.' ])+/";
$str = preg_replace($regex, "<a href='/pretraga.php?q=$0' title='$0' class='actor'>$0</a>", $str);
return $str;
}
Also I want to allow spaces, dashes, dots and single quotes.
Thanks in advance.
You could try this:
$regex = "/(?:[a-zA-Z.\-' ]|[^\\u0000-\\u007F,])+/";
Which converts régime, Coffehouse Coder, Apple into
'<a href='/pretraga.php?q=régime' title='régime' class='actor'>régime</a>,<a href='/pretraga.php?q= Coffehouse Coder' title=' Coffehouse Coder' class='actor'> Coffehouse Coder</a>,<a href='/pretraga.php?q= Apple' title=' Apple' class='actor'> Apple</a>',
here on regex101.com.
The follwing regex should work for you
[^\u0000-\u007F ]|[a-zA-Z-.' ]\g
[^\u0000-\u007F ] : will match all non English Unicode characters.
[a-zA-Z-.' ]: will match English alphabets
For PHP use this : [^\\u0000-\\u007F]|[a-zA-Z-.']
For everyone that is looking for the solve, i found this temporary solution:
$regex = "/([\w-.' \á-\ÿ])+/";
Without dot and stuff but with spaces:
$regex = "/([a-zA-Z \á-\ÿ])+/";
Cheers

How to remove leading characters and the query character with a regular expression in PHP?

I am using preg_replace() and a regular expression to remove all characters before a hyphen (-). I'd like to update the expression to also remove the hyphen itself. The full line of code is shown below in context.
$item['options']['Size'] = preg_replace('/^[^-]*/', '', $item['options']['Size']);
So as it stands let's say I have the below string:
TEST123-150X200
The current preg_replace function will leave me with:
-150X200
I'd like to end up with:
150X200
Could anyone suggest how I can update the regular_expression to achieve this. Thanks
You can add a hyphen at the end of the pattern.
$item['options']['Size'] = preg_replace('/^[^-]*-/', '', $item['options']['Size']);
^
This way, the hyphen is matched (=consumed) and will be removed. Note that [^-] is a negated character class that matches any character but a -. Thus the hyphen was not matched by your original regex.
A non-regex approach:
$item['options']['Size'] = ltrim(strstr($item['options']['Size'], '-'),'-');
See IDEONE demo
<?php
$item = 'TEST123-150X200'; // string here
echo preg_replace('/^[^-]*-/', '', $item);
?>
In addition to the answers/comments given, you could also use a positive lookbehind and replace this:
<?php
$str = "TEST123-150X200";
$regex = '/.*(?<=-)/i';
$item['options']['Size'] = preg_replace($regex, '', $str);
// output: 150X200
?>
Alternatively (as described in the comment), start counting from 1:
$item['options']['Size'] = substr(preg_replace('/^[^-]*/', '', $item['options']['Size']), 1);
I dont think it needs a regex for this...
$str = "TEST123-150X200";
var_dump(end(explode("-", $str))); //string(7) "150X200"
var_dump(ltrim(strstr($str, "-"), "-"));//string(7) "150X200"
var_dump(substr(strrchr($str, "-"), 1) );//string(7) "150X200"

PHP Regex: Remove words less than 3 characters

I'm trying to remove all words of less than 3 characters from a string, specifically with RegEx.
The following doesn't work because it is looking for double spaces. I suppose I could convert all spaces to double spaces beforehand and then convert them back after, but that doesn't seem very efficient. Any ideas?
$text='an of and then some an ee halved or or whenever';
$text=preg_replace('# [a-z]{1,2} #',' ',' '.$text.' ');
echo trim($text);
Removing the Short Words
You can use this:
$replaced = preg_replace('~\b[a-z]{1,2}\b\~', '', $yourstring);
In the demo, see the substitutions at the bottom.
Explanation
\b is a word boundary that matches a position where one side is a letter, and the other side is not a letter (for instance a space character, or the beginning of the string)
[a-z]{1,2} matches one or two letters
\b another word boundary
Replace with the empty string.
Option 2: Also Remove Trailing Spaces
If you also want to remove the spaces after the words, we can add \s* at the end of the regex:
$replaced = preg_replace('~\b[a-z]{1,2}\b\s*~', '', $yourstring);
Reference
Word Boundaries
You can use the word boundary tag: \b:
Replace: \b[a-z]{1,2}\b with ''
Use this
preg_replace('/(\b.{1,2}\s)/','',$your_string);
As some solutions worked here, they had a problem with my language's "multichar characters", such as "ch". A simple explode and implode worked for me.
$maxWordLength = 3;
$string = "my super string";
$exploded = explode(" ", $string);
foreach($exploded as $key => $word) {
if(mb_strlen($word) < $maxWordLength) unset($exploded[$key]);
}
$string = implode(" ", $exploded);
echo $string;
// outputs "super string"
To me, it seems that this hack works fine with most PHP versions:
$string2 = preg_replace("/~\b[a-zA-Z0-9]{1,2}\b\~/i", "", trim($string1));
Where [a-zA-Z0-9] are the accepted Char/Number range.

How to add a space after a point?

I'd like to add a space after any point found with an alphabetic or numeric character just after it (no space found), assuming the next character after the point is not an end of line (cr, lf, ...) character.
preg_replace "/.[a-z0-9]{1}/" with "/. [a-z0-9]/i"
How may I do this in PHP ?
You can use a positive lookahead:
$str = preg_replace("/\.(?=[a-z\d])/i", ". ", $str);
DEMO
You already posted the almost correct answer
$text = preg_replace( '#\.([A-Za-z0-9])#', '. $1', $text );
should do the trick

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

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.

Categories