How can I use preg_match to see if special characters [^'£$%^&*()}{#:'#~?><>,;#|\-=-_+-¬`] exist in a string?
[\W]+ will match any non-word character.
but to match only the characters from the question, use this:
$string="sadw$"
if(preg_match("/[\[^\'£$%^&*()}{#:\'#~?><>,;#\|\\\-=\-_+\-¬\`\]]/", $string)){
//this string contain atleast one of these [^'£$%^&*()}{#:'#~?><>,;#|\-=-_+-¬`] characters
}
Use preg_match. This function takes in a regular expression (pattern) and the subject string and returns 1 if match occurred, 0 if no match, or false if an error occurred.
$input = 'foo';
$pattern = '/[\'\/~`\!##\$%\^&\*\(\)_\-\+=\{\}\[\]\|;:"\<\>,\.\?\\\]/';
if (preg_match($pattern, $input)){
// one or more matches occurred, i.e. a special character exists in $input
}
You may also specify flags and offset for the Perform a Regular Expression Match function. See the documentation link above.
My function makes life easier.
function has_specchar($x,$excludes=array()){
if (is_array($excludes)&&!empty($excludes)) {
foreach ($excludes as $exclude) {
$x=str_replace($exclude,'',$x);
}
}
if (preg_match('/[^a-z0-9 ]+/i',$x)) {
return true;
}
return false;
}
The second parameter ($excludes) may be passed with values you wish to ignore.
Usage
$string = 'testing_123';
if (has_specchar($string)) {
// special characters found
}
$string = 'testing_123';
$excludes = array('_');
if (has_specchar($string,$excludes)) { } // false
For me, this works best:
$string = 'Test String';
$blacklistChars = '"%\'*;<>?^`{|}~/\\#=&';
$pattern = preg_quote($blacklistChars, '/');
if (preg_match('/[' . $pattern . ']/', $string)) {
// string contains one or more of the characters in var $blacklistChars
}
You can use preg_quote to escape charaters to use inside a regex expression:
preg_match('/' . preg_quote("[^'£$%^&*()}{#:'#~?><>,;#|\-=-_+-¬`]", '/') . '/', $string);
http://php.net/manual/en/function.preg-quote.php
This works well for all PHP versions. The resultant is a bool and needs to be used accordingly.
To check id the string contains characters you can use this:
preg_match( '/[a-zA-Z]/', $string );
To check if a string contains numbers you can use this.
preg_match( '/\d/', $string );
Now to check if a string contains special characters, this one should be used.
preg_match('/[^a-zA-Z\d]/', $string);
In case you want to match on special characters
preg_match('/[\'\/~`\!##\$%\^&\*\(\)_\-\+=\{\}\[\]\|;:"\<\>,\.\?\\\]/', $input)
Related
According to PHP manual "If matches is provided, then it is filled with the results of search. $matches[0] will contain the text that matched the full pattern, $matches[1] will have the text that matched the first captured parenthesized subpattern, and so on."
How can I return a value from a string with only knowing the first few characters?
The string is dynamic and will always change whats inside, but the first four character will always be the same.
For example how could I return "Car" from this string "TmpsCar". The string will always have "Tmps" followed by something else.
From what I understand I can return using something like this
preg_match('/(Tmps+)/', $fieldName, $matches);
echo($matches[1]);
Should return "Car".
Your regex is flawed. Use this:
preg_match('/^Tmps(.+)$/', $fieldName, $matches);
echo($matches[1]);
$matches = []; // Initialize the matches array first
if (preg_match('/^Tmps(.+)/', $fieldName, $matches)) {
// if the regex matched the input string, echo the first captured group
echo($matches[1]);
}
Note that this task could easily be accomplished without regex at all (with better performance): See startsWith() and endsWith() functions in PHP.
"The string will always have "Tmps" followed by something else."
You don't need a regular expression, in that case.
$result = substr($fieldName, 4);
If the first four characters are always the same, just take the portion of the string after that.
An alternative way is using the explode function
$fieldName= "TmpsCar";
$matches = explode("Tmps", $fieldName);
if(isset($matches[1])){
echo $matches[1]; // return "Car"
}
Given that the text you are looking in, contains more than just a string, starting with Tmps, you might look for the \w+ pattern, which matches any "word" char.
This would result in such an regular expression:
/Tmps(\w+)/
and altogether in php
$text = "This TmpsCars is a test";
if (preg_match('/Tmps(\w+)/', $text, $m)) {
echo "Found:" . $m[1]; // this would return Cars
}
I have variable like this
$string = "Hello World";
I want to compare its with properly format:
$formatstring = 'anystringornumber/anystringornumber/anystringornumber/anystringornumber/number';
This is my PHP usage:
$key = "Kode Parkir 1/01012015/Shift1/Suhendra/25000";
$regex = '^[A-Za-z]/[A-Za-z]/[A-Za-z]/[A-Za-z]/[0-9]^';
if (preg_match($regex, $key)) {
echo 'Passed';
} else {
echo 'Wrong key';
}
The result always Wrong Key.
Your regex is incorrect instead use
$regex = '~[a-z\d]+/[a-z\d]+/[a-z\d]+/[a-z\d]+/[\d]+~i';
Demo
You want to match alphanumeric character (letter and number), but didn't add the numbers in the regex. Also you missed + to match multiple characters. Secondly don't use ^ for enclosing the pattern. It is used as a special character in regex, which means start of string. You can use # instead. Like this:
$regex = '#[A-Za-z0-9]+/[A-Za-z0-9]+/[A-Za-z0-9]+/[A-Za-z0-9]+/[0-9]+#';
But if you want to use ^ and $ with their special meaning it will be like this :
$regex = '#^[A-Za-z0-9]+/[A-Za-z0-9]+/[A-Za-z0-9]+/[A-Za-z0-9]+/[0-9]+$#';
How can I check if a string has the format [group|any_title] and give me the title back?
[group|This is] -> This is
[group|just an] -> just an
[group|example] -> example
I would do that with explode and [group| as the delimiter and remove the last ]. If length (of explode) is > 0, then the string has the correct format.
But I think that is not quite a good way, isn't it?
So you want to check if a string matches a regex?
if(preg_match('/^\[group\|(.+)\]$/', $string, $m)) {
$title = $m[1];
}
If the group part is supposed to be dynamic as well:
if(preg_match('/^\[(.+)\|(.+)\]$/', $string, $m)) {
$group = $m[1];
$title = $m[2];
}
Use regular expression matching using PHP function preg_match.
You can use for example regexr.com to create and test a regular expression and when you're done, then implement it in your PHP script (replace the first parameter of preg_match with your regular expression):
$text = '[group|This is]';
// replace "pattern" with regular expression pattern
if (preg_match('/pattern/', $text, $matches)) {
// OK, you have parts of $text in $matches array
}
else {
// $text doesn't contain text in expected format
}
Specific regular expression pattern depends on how strictly you want to check your input string. It can be for example something like /^\[.+\|(.+)\]$/ or /\|([A-Za-z ]+)\]$/. First checks if string starts with [, ends with ] and contains any characters delimited by | in between. Second one just checks if string ends with | followed by upper and lower case alphabetic characters and spaces and finally ].
I am trying to verify in PHP with preg_match that an input string contains only "a-z, A-Z, -, _ ,0-9" characters. If it contains just these, then validate.
I tried to search on google but I could not find anything usefull.
Can anybody help?
Thank you !
Use the pattern '/^[A-Za-z0-9_-]*$/', if an empty string is also valid. Otherwise '/^[A-Za-z0-9_-]+$/'
So:
$yourString = "blahblah";
if (preg_match('/^[A-Za-z0-9_-]*$/', $yourString)) {
#your string is good
}
Also, note that you want to put a '-' last in the character class as part of the character class, that way it is read as a literal '-' and not the dash between two characters such as the hyphen between A-Z.
$data = 'abc123-_';
echo preg_match('/^[\w|\-]+$/', $data); //match and output 1
$data = 'abc..';
echo preg_match('/^[\w|\-]+$/', $data); //not match and output 0
You can use preg_replace($pattern, $replacement, $subject):
if (preg_replace('/[A-Za-z0-9\-\_]/', '', $string)) {
echo "Detect non valid character inside the string";
}
The idea is to remove any valid chars, if the result is NOT empty do the code.
I know that there is the function ctype_alpha, though this one will return FALSE when the string contains spaces (white space character).
How do I allow alpha characters and spaces, but nothing else?
$is_alpha_space = ctype_alpha(str_replace(' ', '', $input)));
or
$is_alpha_space = preg_match('/^[a-z\s]*$/i', $input);
if (preg_match("^/[a-zA-Z ]+$/", $input)) {
// input matches
}
Demo: http://ideone.com/jp6Wi
Docs: http://php.net/manual/en/function.preg-match.php
ctype_alpha(preg_replace('/\s/', '', $mystring))
The inner expression returns the string without spaces, and then you use ctype_alpha`` as you wish
Removing the spaces is the way to go, but remember ctype_alpha results in a false on an empty string these days! Below the method I use...
function validateAlpha($valueToValidate, $spaceAllowed = false) {
if ($spaceAllowed) {
$valueToValidate = str_replace(' ', '', $valueToValidate);
}
if (strlen($valueToValidate) == 0) {
return true;
}
return ctype_alpha($valueToValidate);
}
I would work around with a Simple regex and with the php function preg_match() like this:
if(preg_match("/^[a-zA-Z ]+$/", $varToCheck)){
//your code here
}
The important part here is the regex that identifies the parts you want, in my case I wanted text for a name field and with spaces like the case in here.[a-z] is the range from a to z, A-Z are the range from A to Z and the " " at the end represents the spaces.
Hope this helps someone.