Regex to allow A-Z, - and ' - php

I am trying to get this Regex to work to validate a Name field to only allow A-Z, ' and -.
So far I am using this which is working fine apart from it wont allow an apostrophe.
if (preg_match("/[^a-zA-Z'-]+/",$firstname)) {
// do something
}
I would like it to only allow A-Z, - (dash) and an ' (apostrophe). It works for the A-Z and the - but still wont work for the '
Could someone please provide an example?
Thanks

if (preg_match("/^[A-Z'-]+$/",$firstname)) {
// do something
}
The caret ^ inside a character class [] will negate the match. The way you have it, it means if the $firstname contains characters other than a-z, A-Z, ', and -.

Your code already does what you want it to:
<?php
$data = array(
// Valid
'Jim',
'John',
"O'Toole",
'one-two',
"Daniel'Blackmore",
// Invalid
' Jim',
'abc123',
'$##$%##$%&*(*&){}//;;',
);
foreach($data as $firstname){
if( preg_match("/[^a-zA-Z'-]+/",$firstname) ){
echo 'Invalid: ' . $firstname . PHP_EOL;
}else{
echo 'Valid: ' . $firstname . PHP_EOL;
}
}
... prints:
Valid: Jim
Valid: John
Valid: O'Toole
Valid: one-two
Valid: Daniel'Blackmore
Invalid: Jim
Invalid: abc123
Invalid: $##$%##$%&*(*&){}//;;
The single quote does not have any special meaning in regular expressions so it needs no special treatment. The minus sign (-), when inside [], means range; if you need a literal - it has to be the first or last character, as in your code.
Said that, the error (if any) is somewhere else.

"/[^a-zA-Z'-]+/" actually matches everything but a-zA-z'-, if you put the ^ in to indicate the start-of-string, you should put it outside the brackets.
Also, the '- part of your expression is possibly being interpreted as a range, so you should escape the - as #Tom answered or escape the , as someone else answered

From what I see. Following Regex should work fine:
if (preg_match("/^[A-Z\'\-]+$/",$firstname)) {
// do something
}
Here I have escaped both apostrophe and dash. I have tested this in an online Regex tester and works just fine.
Give it a try

Your regexp should look like this:
preg_match("/^[A-Z\'-]+$/",$firstname);
maches: AB A-B AB-'
does not match: Ab a-B AB# <empty string>

if (preg_match("/^[a-zA-Z -]*$/", $firstname)) {
// do something here
}
I have used this, This will work fine. Use It.

Related

Create a function to find a specific word in the title

I have the following title formation on my website:
It's no use going back to yesterday, because at that time I was... Lewis Carroll
Always is: The phrase… (author).
I want to delete everything after the ellipsis (…), leaving only the sentence as the title. I thought of creating a function in php that would take the parts of the titles, throw them in an array and then I would work each part, identifying the only pattern I have in the title, which is the ellipsis… and then delete everything. But when I do that, in the X space of my array, it returns the following:
was...
In position 8 of the array comes the word and the ellipsis and I don't know how to find a pattern to delete the author of the title, my pattern was the ellipsis. Any idea?
<?php
$a = get_the_title(155571);
$search = '... ';
if(preg_match("/{$search}/i", $a)) {
echo 'true';
}
?>
I tried with the code above and found the ellipsis, but I needed to bring it into an array to delete the part I need. I tried something like this:
<?php
define('WP_USE_THEMES', false);
require('./wp-blog-header.php');
global $wpdb;
$title_array = explode(' ', get_the_title(155571));
$search = '... ';
if (array_key_exists("/{$search}/i",$title_array)) {
echo "true";
}
?>
I started doing it this way, but it doesn't work, any ideas?
Thanks,
If you use regex you need to escape the string as preg_quote() would do, because a dot belongs to the pattern.
But in your simple case, I would not use a regex and just search for the three dots from the end of the string.
Note: When the elipsis come from the browser, there's no way to detect in PHP.
$title = 'The phrase... (author).';
echo getPlainTitle($title);
function getPlainTitle(string $title) {
$rpos = strrpos($title, '...');
return ($rpos === false) ? $title : substr($title, 0, $rpos);
}
will output
The phrase
First of all, since you're working with regular expressions, you need to remember that . has a special meaning there: it means "any character". So /... / just means "any three characters followed by a space", which isn't what you want. To match a literal . you need to escape it as \.
Secondly, rather than searching or splitting, you could achieve what you want by replacing part of the string. For instance, you could find everything after the ellipsis, and replace it with an empty string. To do that you want a pattern of "dot dot dot followed by anything", where "anything" is spelled .*, so \.\.\..*
$title = preg_replace('/\.\.\..*/', '', $title);

PHP - Regex for a string of special characters

Morning SO. I'm trying to determine whether or not a string contains a list of specific characters.
I know i should be using preg_match for this, but my regex knowledge is woeful and i have been unable to glean any information from other posts around this site. Since most of them just want to limit strings to a-z, A-Z and 0-9. But i do want some special characters to be allowed, for example: ! # £ and others not in the below string.
Characters to be matched on: # $ % ^ & * ( ) + = - [ ] \ ' ; , . / { } | \ " : < > ? ~
private function containsIllegalChars($string)
{
return preg_match([REGEX_STRING_HERE], $string);
}
I originally wrote the matching in Javascript, which just looped through each letter in the string and then looped through every character in another string until it found a match. Looking back, i can't believe i even attempted to use such an archaic method. With the advent of json (and a rewrite of the application!), i'm switching the match to php, to return an error message via json.
I was hoping a regex guru could assist with converting the above string to a regex string, but any feedback would be appreciated!
Regexp for a "list of disallowed character" is not mandatory.
You may have a look at strpbrk. It should do the job you need.
Here's an example of usage
$tests = array(
"Hello I should be allowed",
"Aw! I'm not allowed",
"Geez [another] one",
"=)",
"<WH4T4NXSS474K>"
);
$illegal = "#$%^&*()+=-[]';,./{}|:<>?~";
foreach ($tests as $test) {
echo $test;
echo ' => ';
echo (false === strpbrk($test, $illegal)) ? 'Allowed' : "Disallowed";
echo PHP_EOL;
}
http://codepad.org/yaJJsOpT
return preg_match('/[#$%^&*()+=\-\[\]\';,.\/{}|":<>?~\\\\]/', $string);
$pattern = preg_quote('#$%^&*()+=-[]\';,./{}|\":<>?~', '#');
var_dump(preg_match("#[{$pattern}]#", 'hello world')); // false
var_dump(preg_match("#[{$pattern}]#", 'he||o wor|d')); // true
var_dump(preg_match("#[{$pattern}]#", '$uper duper')); // true
Likely, you can cache the $pattern, depending on your implementation.
(Though looking outside of regular expressions, you're best of with strpbrk as mentioned here too)
I think what you're looking for can be greatly simplified by including the characters that you want to allow like so:
preg_match('/[^\w!#£]/', $string)
Here's a quick breakdown of what's happening:
[^] = not included
\w = letters and numbers
! # £ = the list of characters you would also like to allow

Regex with + sign

I'm using this code to validate string.
$countrecipient ='0123456789';
preg_match('/^[0]{1}[1]{1}[0-9]{1}[0-9]{7}?$/', $countrecipient)
How if I want to validate if the number contain "+" sign in front or not?
Such as :
$countrecipient ='+0123456789';
and still need to validate the rest of the string.
I tried this:
if(preg_match('/^[+]{1}[6]{1}[0]{1}[1]{1}[0-9]{1}[0-9]{7}?$/', $countrecipient))
{
echo "Ok";
}
else
{
echo "Error";
}
It works in my pc but I'm not sure why my customer is complaining it shows him error.
Thank you.
For an optional plus in front you could use:
preg_match('/^\+?[0]{1}[1]{1}[0-9]{1}[0-9]{7}?$/', $countrecipient);
Notice how I have escaped the + with a backslash? This is because it is a regex keyword which means 1 instance or more.
$countrecipient ='0123456789';
preg_match('/^[0]{1}[1]{1}[0-9]{1}[0-9]{7}?$/', $countrecipient)
You're making things unnecessarily complicated. "[0]{1}[1]{1}[0-9]{1}" reduces to simply "01[0-9]".
To have an optional + on the front, your basic idea of using [+] should work. Let's see...
$countrecipient ='+0123456789';
if(preg_match('/^[+]{1}[6]{1}[0]{1}[1]{1}[0-9]{1}[0-9]{7}?$/', $countrecipient))
...again this can be simplified, but it simplies to /^[+]601[0-9][0-9]{7}?$/. Where did the 6 after the + come from? Does this account for your problem?
Plus has a special meaning in PCRE, it's called quantifier and has meaning of {1,}.
You may either put in into character group specification like this [+] which would literally mean one of following characters: array( '+') or escape it with \ so you'll get: \+.
Also adding {1} is implicit and you don't have to add it after one character. If you were doing this matching foo would look like: f{1}o{1}o{1}, ehm f{1}o{2} instead of foo :)
If you want to match both 0123456789 and +012345678 you should use {0,1} which has "shortcut" ?. Than your pattern would look like: /\+?/. I guess your desired regexp is:
/^\+?0?1?[0-9]([0-9]{7})?$/
The simplified form of your regex is
/\+?01[0-9]{8}/
However I recommend you use intval, is_int, ctype_digit to accomplish this.
if(intval($str)<=100000000){
// found it.
}
Based on regexp you put in the section you tried: "...preg_match('/^[+]{1}[6]{1}[0]{1}[1]{1}[0-9]{1}[0-9]{7}?$/'..."
If you would validate the string AND check if there is a '+' or not, you could use something like this:
if(preg_match('/(\+)?6011[0-9][0-9]{7}?$/', $countrecipient, $matches))
{
if ($matches[1] == '+') {
echo "Ok WITH PLUS";
} else {
echo "Ok without PLUS";
}
}
else
{
echo "Error";
}

PHP Regular Expression Failing

My current regular expression should be correct, though I wouldn't expect so, it doesn't work properly. It won't return "Got Match"
My currrent code is as follows:
$id = "http://steamcommunity.com/id/TestID";
if (preg_match("^http://steamcommunity\.com/id/.*?\n$", $id)) {
print "Got match!\n";
}
You're missing delimiters on your regex:
if (preg_match("#^http://steamcommunity\.com/id/.*?\n$#", $id)) {
^--here ^--here
Note that I've used # as the delimiter here, since that saves you having to escape all of the internal / charrs, if you'd used the traditional / as the delimiter.
You need a delimiter, like this:
if (preg_match("#^http://steamcommunity\.com/id/.*?$#", $id)) {
^ ^
And what's with the newline at the end? Surely you don't need that.
You're missing delimiters. For example:
"#^http://steamcommunity\.com/id/.*?\n$#"
Also, you're trying to match a newline (\n) that isn't in your string.
You need to add the pattern delimiter:
$id = "http://steamcommunity.com/id/TestID";
if (preg_match("#^http://steamcommunity\.com/id/.*?(\n|$)#", $id)) {
print "Got match!\n";
}
There are a couple of things that are wrong with it. First of all, you need to delimit the start and end of your regex with a character. I used #. You're also matching for a new line at the end of your regex, which you don't have and likely won't ever have in your string.
<?php
$id = "http://steamcommunity.com/id/TestID";
if (preg_match("#^http://steamcommunity\.com/id/.*?$#", $id)) {
print "Got match!\n";
}
?>
http://codepad.viper-7.com/L7XctT
First of all, your regex shouldn't even compile because it's missing delimiters.
if (preg_match("~^http://steamcommunity\.com/id/.*?\n$~", $id)) {
^---- these guys here -----^
Second of all, why do you have a \n if your string doesn't contain a new line?
And finally, why are you using regex at all? Effectively, you are just trying to match a constant string. This should be equivalent to what you are trying to match:
if (strpos($id, 'http://steamcommunity.com/id/') === 0) {
You need to have starting and ending delimiter in your pattern like /pattern/ or #pattern# or with brackets (pattern). Why is that? To have some pattern modifiers after ending delimiter like #pattern#i (ignore case)
preg_match('(^http://steamcommunity\.com/id/.*?\n$)', $id)
As the say your patten is start and end wrong. (Delimiter)
But this will be a better match of a 64-bit Steam ID. (Minimum 17 and Maximum 25 numbers)
if( preg_match("#^http://steamcommunity\.com/id/([0-9]{17,25})#i", $id, $matches) )
{
echo "Got match! - ".$matches;
}
I believe that there is no need for you to require that the string must end with a line break.
Explanation.
http://steamcommunity\.com/id/([0-9]{17,25})
^--- string ---^^-- Regexp --^
[0-9] - Match a number between 0 to 9
{17,25} - Make 17 to 25 matches
() - Returns match
Or use pattern as those (It is the same):
/^http:\/\/steamcommunity\.com\/id\/([0-9]{17,25})/i
(^http://steamcommunity\.com/id/([0-9]{17,25}))i
Regular Expressions PHP Tutorial
Online regular expression testing <- Dont use delimiter.
<?php
# URL that generated this code:
# http://txt2re.com/index-php.php3?s=http://steamcommunity.com/id&-1
$txt='http://steamcommunity.com/id';
$re1='(http:\\/\\/steamcommunity\\.com\\/id)'; # HTTP URL 1
if ($c=preg_match_all ("/".$re1."/is", $txt, $matches))
{
$httpurl1=$matches[1][0];
print "($httpurl1) \n";
}
#-----
# Paste the code into a new php file. Then in Unix:
# $ php x.php
#-----
?>
Resorces:
http://txt2re.com/index.php3?s=http://steamcommunity.com/id&-1

PHP: preg_match

i need to write a case which only except the a-zA-Z0-9 characters with underscore and white space(1 or more than 1) and ignore all rest of the characters.I wrote a code but its not working properly.
In those case should be wrong but its show OK
1) test msg#
2) test#msg
3) test!msg
also those should be OK but currently shows wrong.
1) test msg.-(Two white space)
what i should to change in my code .pls help and see my code below.
$message=$_GET['msg'];
if(preg_match('/[^A-Za-z0-9]\W/',$message))
{
echo "Wrong";
}
else
{
echo "OK";
}
Here's an optimized version of the one left by riad:
$message = $_GET['msg'];
if ( preg_match('/^[a-z0-9_ ]+$/i', $message) )
{
echo 'Ok';
}
else
{
echo 'Wrong';
}
I've removed the A-Z (uppercase) from the regular expression since the i modifier is used.
I'd also like to explain what you did wrong in the example you provided.
First, by putting the ^ inside the square brackets ([]), you're essentially doing the opposite of what you were trying to do. Place a ^ inside the square brackets means "not including."
You were missing a *, + or ? at the end of the square bracket, unless you only wanted to match a single character. The * character means 0 or more, + means 1 or more and ? means 0 or 1.
The \W means any non-word character. That's probably not what you wanted.
Finally, to starting a regular expression with ^ means that the beginning of the string you're string to match must start with whatever is after the ^. Ending the regular expression with a $ means that the string must end with the characters preceding the $.
So by typing /^[a-z0-9_ ]+$/i you're saying match a string that starts with a-z0-9_ or a space, that contains at least of those characters (+) and ends.
PHP has a lot of documentation of the PCRE regular syntax which you can find here: http://ca2.php.net/manual/en/reference.pcre.pattern.syntax.php.
$message=$_GET['msg'];
if(preg_match('/^[a-zA-Z0-9_ ]+$/i',$message))
{
echo "Wrong";
}
else
{
echo "OK";
}

Categories