Allow only [a-z][A-Z][0-9] in string using PHP - php

How can I get a string that only contains a to z, A to Z, 0 to 9 and some symbols?

You can filter it like:
$text = preg_replace("/[^a-zA-Z0-9]+/", "", $text);
As for some symbols, you should be more specific

You can test your string (let $str) using preg_match:
if(preg_match("/^[a-zA-Z0-9]+$/", $str) == 1) {
// string only contain the a to z , A to Z, 0 to 9
}
If you need more symbols you can add them before ]

Don't need regex, you can use the Ctype functions:
ctype_alnum: Check for alphanumeric character(s)
ctype_alpha: Check for alphabetic character(s)
ctype_cntrl: Check for control character(s)
ctype_digit: Check for numeric character(s)
ctype_graph: Check for any printable character(s) except space
ctype_lower: Check for lowercase character(s)
ctype_print: Check for printable character(s)
ctype_punct: Check for any printable character which is not whitespace or an alphanumeric character
ctype_space: Check for whitespace character(s)
ctype_upper: Check for uppercase character(s)
ctype_xdigit: Check for character(s) representing a hexadecimal digit
In your case use ctype_alnum, example:
if (ctype_alnum($str)) {
//...
}
Example:
<?php
$strings = array('AbCd1zyZ9', 'foo!#$bar');
foreach ($strings as $testcase) {
if (ctype_alnum($testcase)) {
echo 'The string ', $testcase, ' consists of all letters or digits.';
} else {
echo 'The string ', $testcase, ' don\'t consists of all letters or digits.';
}
}
Online example: https://ideone.com/BYN2Gn

Both these regexes should do it:
$str = preg_replace('~[^a-z0-9]+~i', '', $str);
Or:
$str = preg_replace('~[^a-zA-Z0-9]+~', '', $str);

A shortcut will be as below also:
if (preg_match('/^[\w\.]+$/', $str)) {
echo 'Str is valid and allowed';
} else
echo 'Str is invalid';
Here:
// string only contain the a to z , A to Z, 0 to 9 and _ (underscore)
\w - matches [a-zA-Z0-9_]+
Hope it helps!

If you need to preserve spaces in your string do this
$text = preg_replace("/[^a-zA-Z0-9 ]+/", "", $text);
Please note the way I have added space between 9 and the closing bracket. For example
$name = "!#$John Doe";
echo preg_replace("/[^a-zA-Z0-9 ]+/", "", $name);
the output will be:
John Doe
Spaces in the string will be preserved.
If you fail to include the space between 9 and the closing bracket the output will be:
JohnDoe
Hope it helps someone.

The best and most flexible way to accomplish that is using regular expressions.
But I`m not sure how to do that in PHP but this article can help. link

Related

How to remove a character from a string only if it follows a number?

I have several rows of data that are in address format, I want to remove the house number from each address.
So far I have been able to remove the number using:
<?php
$string = '25a Test Lane';
if (preg_match("/[0-9]/", $string)) {
$string = preg_replace("/[0-9]/", "", $string);
}
?>
$string then becomes 'a Test Lane' - but how would I go about removing 'a' as well? Bearing in mind the 'a' could be any letter following a number. I'd want to remove any character that immediately follows the number (no space in between).
You can use
trim(preg_replace("/\b\d+[a-zA-Z]*\b/", "", $string))
trim(preg_replace("/\b\d+[a-zA-Z]?\b/", "", $string))
Here is the regex demo. NOTE: if you only want to allow a single letter after the number, replace * with ? in [a-zA-Z]*.
Details:
\b - a word boundary
\d+ - one or more digits
[a-zA-Z]* - zero or more ASCII letters
[a-zA-Z]? - one or zero ASCII letters
\b - a word boundary.
See the PHP demo:
$string = '25a Test Lane';
$string = trim(preg_replace("/\b\d+[a-zA-Z]*\b/", "", $string));
echo $string;
// => Test Lane

PHP preg_replace expect digits after a dash

Hi i'm trying to replace all digits or numbers in a string except digits after dash by blank space
For example I have this :
$string = "1234 Example-1234";
And I want to have only "Example-1234"
I tried preg_replace('/\-?\d+/','',$string); but even digits after dash are replaced
Edited: Thanks everyone i tried all of your answers and it works well !
If you want to just skip all digits preceded with - and remove all others, use
'~-\d+(*SKIP)(*F)|\d+~'
See the regex demo
Note you would like to trim the result or add \s* around \d+ pattern.
Pattern details:
-\d+(*SKIP)(*F) - match -, 1+ digits and skip this match
| - or
\d+ - 1 or more digits
See the PHP demo:
$str = '1234 Example-1234';
$res = preg_replace('/-\d+(*SKIP)(*F)|\s*\d+/', '', $str);
echo trim($res); // => Example-1234
The solution using regex negative lookbehind assertion (?<!a)b:
$str = "1234 Example-1234";
$str = preg_replace('/(?<![0-9-])\d+/', '', $str);
print_r($str);
The output:
Example-1234
Because you are looking for words that contain a dash, you can achieve this by to splitting the string via spaces, loop through the array values until you find a string with a dash, and then output from there onwards.
$string = "1234 Example-1234";
$words = explode(" ", $string);
foreach($words as $word) {
if (strpos($word, '-') !== false) {
echo $word;
break; // delete this line if there are multiple instances of words with dashes in your string
}
}
This will output Example-1234.
You can see a working example here
ONLINE Regex tester : https://regex101.com/r/ykUWfM/3
<?php
$string = "1234 Example-1234";
echo preg_replace('/-(\d+)/','',$string);
?>
OUTPUT: before - convert into string
1234 Example
NOTE: Before - its get the string before dash -
OR
Demo: https://regex101.com/r/ykUWfM/2
<?php
$string = "1234 Example-1234";
echo preg_replace('/(?<![0-9-])\s*\d+/','',$string);
?>
OUTPUT:
Example-1234

How can I check whether is a string contains only English letters?

I use PHP and I need to check whether is a string made of just
English Lowercase letter
dash
underline?
Something like this:
if ( /* the condition */ ) {
// Yes, all characters of the string are English lowercase letters or dash or underline
} else {
// No, there is at least one unexpected character
}
Here is some examples:
$str = "test"; // true
$str = "test_-'; // true
$str = "t-s"; // true
$str = "test1"; // false
$str = "Test"; // false
$str = "test?"; // false
To match a whole string that only consists of 1 or more lowercase ASCII letters, hyphen or underscores, use
/^[-a-z_]+$/D
See the regex demo
Details:
^ - start of string
[-a-z_]+ - 1 or more ASCII lowercase letters, hyphens or underscores
$ - end of string
/D - the modifier that will make $ match the very end of the string (otherwise, $ will also match a newline that appears at the end of the string).
PHP:
if (preg_match('/^[-a-z_]+$/D', $input)) {
// Yes, all characters of the string are English lowercase letters or dash or underline
} else {
// No, there is at least one unexpected character
}
Use the PHP function
preg_match()
with this regular expression:
$regex = [a-z\_\-]+
The \ are to escape out the underscore and dash. + means you have to have at least 1 character.
This is a handy tool for regular expressions http://www.regexpal.com/
Try this on for size
/**
* Test if a string matches our criteria
*/
function stringTestOk($str) {
return !(preg_match_all('/[^a-z_\-]/', $str) > 0);
}
// Examples
foreach(['test', 'test_-', 't-s', 'test1', 'Test', 'test?'] as $str) {
echo $str, ' ', (stringTestOk($str) ? 'true' : 'false'), PHP_EOL;
}

Remove all non-matching characters in PHP string?

I've got text from which I want to remove all characters that ARE NOT the following.
desired_characters =
0123456789!&',-./abcdefghijklmnopqrstuvwxyz\n
The last is a \n (newline) that I do want to keep.
To match all characters except the listed ones, use an inverted character set [^…]:
$chars = "0123456789!&',-./abcdefghijklmnopqrstuvwxyz\n";
$pattern = "/[^".preg_quote($chars, "/")."]/";
Here preg_quote is used to escape certain special characters so that they are interpreted as literal characters.
You could also use character ranges to express the listed characters:
$pattern = "/[^0-9!&',-.\\/a-z\n]/";
In this case it doesn’t matter if the literal - in ,-. is escaped or not. Because ,-. is interpreted as character range from , (0x2C) to . (0x2E) that already contains the - (0x2D) in between.
Then you can remove those characters that are matched with preg_replace:
$output = preg_replace($pattern, "", $str);
$string = 'This is anexample $tring! :)';
$string = preg_replace('/[^0-9!&\',\-.\/a-z\n]/', '', $string);
echo $string; // hisisanexampletring!
^ This is case sensitive, hence the capital T is removed from the string. To allow capital letters as well, $string = preg_replace('/[^0-9!&\',\-.\/A-Za-z\n]/', '', $string)

preg_match all words start with an #?

i'm not very firm with regular Expressions, so i have to ask you:
How to find out with PHP if a string contains a word starting with # ??
e.g. i have a string like "This is for #codeworxx" ???
I'm so sorry, but i have NO starting point for that :(
Hope you can help.
Thanks,
Sascha
okay thanks for the results - but i did a mistake - how to implement in eregi_replace ???
$text = eregi_replace('/\B#[^\B]+/','\\1', $text);
does not work??!?
why? do i not have to enter the same expression as pattern?
Match anything with has some whitespace in front of a # followed by something else than whitespace:
$ cat 1812901.php
<?php
echo preg_match("/\B#[^\B]+/", "This should #match it");
echo preg_match("/\B#[^\B]+/", "This should not# match");
echo preg_match("/\B#[^\B]+/", "This should match nothing and return 0");
echo "\n";
?>
$ php 1812901.php
100
break your string up like this:
$string = 'simple sentence with five words';
$words = explode(' ', $string );
Then you can loop trough the array and check if the first character of each word equals "#":
if ($stringInTheArray[0] == "#")
Assuming you define a word a sequence of letters with no white spaces between them, then this should be a good starting point for you:
$subject = "This is for #codeworxx";
$pattern = '/\s*#(.+?)\s/';
preg_match($pattern, $subject, $matches);
print_r($matches);
Explanation:
\s*#(.+?)\s - look for anything starting with #, group all the following letters, numbers, and anything which is not a whitespace (space, tab, newline), till the closest whitespace.
See the output of the $matches array for accessing the inner groups and the regex results.
#OP, no need regex. Just PHP string methods
$mystr='This is for #codeworxx';
$str = explode(" ",$mystr);
foreach($str as $k=>$word){
if(substr($word,0,1)=="#"){
print $word;
}
}
Just incase this is helpful to someone in the future
/((?<!\S)#\w+(?!\S))/
This will match any word containing alphanumeric characters, starting with "#." It will not match words with "#" anywhere but the start of the word.
Matching cases:
#username
foo #username bar
foo #username1 bar #username2
Failing cases:
foo#username
#username$
##username

Categories