I want to get result from preg_match() in this case.
$regex = '/[A-Z][a-z][0-9]/i';
What is the right code to get result below.
preg_match($regex, 'phpversion7') //return false
preg_match($regex, 'Phpversion7') //return true
preg_match($regex, 'Phpversion') //return false
preg_match($regex, 'R1985y2528') //return true
preg_match($regex, 'R19852528') //return false
Simple asign a variable to each preg_match () statement which will store a boolean
Not very clear what you want, but I guess you need something like:
/^[A-Z](?=.*[a-z])(?=.*\d)[a-zA-Z\d]+$/
This regex matches strings that begin with a capital letter and contain at least one letter and at leat one digit.
Explanation:
/ : regex delimiter
^ : start of string
[A-Z] : a capital letter
(?=.*[a-z]) : lookahead, a small letter must be present in the string
(?=.*\d) : lookahead, a digit must be present in the string
[a-zA-Z\d]+ : the whole string must contains only letters and digits.
$ : end of string
/ : regex delimiter
Related
I have this regular expression /^(string#)([^#\s\\\\]|(\\\d{3}))*$/.
It's supposed to accept strings that start with string#, then all characters but #, \, or any whitespace characters can follow. \ can only appear when it's followed by 3 digits.
When I test this regex with the string string#test\07test on regex101.com and phpliveregex.com, no matches are found (correctly), but preg_match() returns true for the same string.
What am I doing wrong?
Thank you
UPDATE:
$regex = "/^(string#)([^#\s\\\\]|(\\\d{3}))*$/";
preg_match($regex, 'string#test\07test'); # this returns false, as it should
preg_match($regex, "string#test\07test"); # this returns true
The test string is taken from a file using fgets() and stored in a variable, though, so I can't pass it to preg_match() and put apostrophes around it, I need to pass the variable ($string, for example), and preg_match($regex, $string) incorrectly returns true again.
First things first:
'\07' is a string of length 3 beginning with a backslash character.
"\07" is a string of length 1 consisting of ASCII x'07'
Interactive shell
php > echo strlen('\07');
3
php > echo strlen("\07");
1
php >
See PHP Strings
Regex:
/^string#(?:[^#\s\\]|\\(?=\d{3}))*$/
See Regex Demo
^ Matches start of string.
string# Matches string#.
[^#\s\\] Matches any character other than #, white space or \.
| or
\\(?=\d{3}) Matches \ if followed by 3 digits.
(?: expression 3 through 5)* matched 0 or more times.
$ Matches the end of string.
Code:
<?php
$tests = [
'abcd',
'string# test',
'string##test',
'string#\07test',
'string#\075test',
'string#test'
];
$regex = '/^string#(?:[^#\s\\\\]|\\\\(?=\d{3}))*$/';
foreach ($tests as $test) {
if (preg_match($regex, $test)) {
echo "$test\n";
}
}
Prints:
string#\075test
string#test
I want to match letters and numbers, but not only numbers.
So I want to create a preg_match() pattern to filter like this:
eg:
no123 true
123no true
123456 false
letters true
So we must have at least one letter. There can be any amount of digits before it and any amount of alphanumeric characters is allowed until end of the string.
/^\d*[a-z][a-z\d]*$/i
^ start of string
\d* any amount of digits
[a-z] one letter
[a-z\d]* any amount of alphanumeric characters
$ until end of the string
i flag for caseless matching
See this demo at regex101
Using a SKIP-FAIL pattern will outperform Toto's pattern (and MH2K9's answer is incorrect as it doesn't allow all alphabetical matches). You can test their patterns on the sample text in my demo link.
/^\d+$(*SKIP)(*FAIL)|^[a-z\d]+$/i
Pattern Demo Link
This "disqualifies" purely numeric strings, and matches mixed (numeric-alphabetical) and purely alphabetical strings.
Code: (Demo)
$string='test123';
var_export(preg_match('/^\d+$(*SKIP)(*FAIL)|^[a-z\d]+$/i',$string)?true:false);
Output:
true
UPDATE: Regular expressions aside, this task logic can be performed by two very simple non-regex calls: ctype_alnum() and ctype_digit()
Code: (Demo)
$tests = [
'no123', // true
'123no', // true
'123456', // false
'letters', // true
];
foreach ($tests as $test) {
echo "$test evaluates as " , (ctype_alnum($test) && !ctype_digit($test) ? 'true' : 'false') , "\n";
}
Output:
no123 evaluates as true
123no evaluates as true
123456 evaluates as false
letters evaluates as true
You can try this Regex. It checks both number and letter at least one.
(?=.*[0-9])(?=.*[a-zA-Z])([a-zA-Z0-9]+)$
According to your comment: "only letters vaild but only number invalid.", this wil do the job:
if (preg_match('/^(?=.*[a-z])[a-z0-9]+$/i', $inputString)) {
// valid
} else {
// invalid
}
Explanation:
/ : regex delimiter
^ : start of string
(?=.*[a-z]) : lookahead, make sure we have at least one letter
[a-z0-9]+ : string contains only letters and numbers
$ : end of string
/i : regex delimiter + flag case insensitive
I'm trying to match any strings that doesn't start with "false1" or "false2", and ends with true, but the regex isn't matching for some reason. What am I doing wrong?
$text = "start true";
$regex = "~(?:(^false1|false2).+?) true~";
if (preg_match($regex, $text, $match)) {
echo "true";
}
Expected Result:
true
Actual Result:
null
You may use negative lookahead.
^(?!false[12]).*true$
If you really want to use boundaries then try this,
^(?!false[12]\b).*\btrue$
DEMO
Update:
^(?!.*false[12]\b).*\btrue$
(?!.*false[12]\b) negative lookahead which asserts that the string would contain any char but not the sub-string false1 or false2 and it must ends with the string true, that's why we added true$ at the last.
Consider example:
$mystring = "us100ch121jp23uk12";
I) I want to change value of jp by adding +1 so that makes the string into
us100ch121jp24uk12
suppose if
II) Is there a way to seperate the numeric part and alphabetic part in the above string into:
[us , 100]
[ch,121]
[jp,24]
[us,12]
my code:
$string = "us100ch121jp23uk12";
$search_for = "us";
$pairs = explode("[]", $string); // I dont know the parameters.
foreach ($pairs as $index=>$pair)
{
$numbers = explode(',',$pair);
if ($numbers[0] == $search_for){
$numbers[1] += 1; // 23 + 1 = 24
$pairs[index] = implode(',',$numbers); //push them back
break;
}
}
$new_string = implode('|',$pairs);
using Evan sir's suggestions
$mystring = "us100ch121jp22uk12";
preg_match_all("/([A-z]+)(\d+)/", $mystring, $output);
//echo $output[0][4];
foreach($output[0] as $key=>$value) {
// echo "[".$value."]";
echo "[".substr($value, 0, 2).",".substr($value, 2, strlen($value) - 2)."]"."<br>";
}
If you use preg_match_all("/([A-z]+)(\d+)/", $string, $output);, it will return an array to $output that contains three arrays. The first array will be country number strings (eg 'us100'). The second will contain country strings (eg 'us'). The third will contain the numbers (eg '100').
Since the second and third arrays will have matching indexes ($output[1][0] will be 'us' and $output[2][0] will be '100'), you could just cycle through those and do whatever you'd like to them.
Here is more information about using regular expressions in PHP. The site also contains information about regular expressions in general, which are a useful tool for any programmer!
You can do it using regular expressions in PHP. See tutorial:
http://w3school.in/w3schools-php-tutorial/php-regular-expression/
Function Description
ereg_replace() The ereg_replace() function finds for string specified by pattern and replaces pattern with replacement if found.
eregi_replace() The eregi_replace() function works similar to ereg_replace(), except that the search for pattern in string is not case sensitive.
preg_replace() The preg_replace() function works similar to ereg_replace(), except that regular expressions can be used in the pattern and replacement input parameters.
preg_match() The preg_match() function finds string of a pattern and returns true if pattern matches false otherwise.
Expression Description
[0-9] It matches any decimal digit from 0 through 9.
[a-z] It matches any character from lowercase a through lowercase z.
[A-Z] It matches any character from uppercase A through uppercase Z.
[a-Z] It matches any character from lowercase a through uppercase Z.
p+ It matches any string containing at least one p.
p* It matches any string containing zero or more p’s.
p? It matches any string containing zero or more p’s. This is just an alternative way to use p*.
p{N} It matches any string containing a sequence of N p’s
p{2,3} It matches any string containing a sequence of two or three p’s.
p{2, } It matches any string containing a sequence of at least two p’s.
p$ It matches any string with p at the end of it.
^p It matches any string with p at the beginning of it.
[^a-zA-Z] It matches any string not containing any of the characters ranging from a through z and A through Z.
p.p It matches any string containing p, followed by any character, in turn followed by another p.
^.{2}$ It matches any string containing exactly two characters.
<b>(.*)</b> It matches any string enclosed within <b> and </b>.
p(hp)* It matches any string containing a p followed by zero or more instances of the sequence hp.
you also can use JavaScript:
http://www.w3schools.com/jsref/jsref_obj_regexp.asp
Count character '_' in start line
example :
subject = '_abcd_abc'; // return 1
or
subject = '__abcd_abc'; // return 2
or
subject = '___abcd_abc'; // return 3
everyone help me ~
I use PHP
If you are sure the start of the string contains _, you can do this with just strspn():
echo strspn('___abcd_abc', '_');
// -> 3
If there might be no leading underscores, you can still do this without a regex using strlen and ltrim:
strlen($str) - strlen(ltrim($str, "_"));
This counts the string length, then subtracts the string length without the underscores on the left, the result being the number of underscores.
strspn()
ltrim()
strlen()
Try this:
return preg_match('/^_+/', $str, $match) ? strlen($match[0]) : 0;
If preg_match finds a match, $match[0] will contain that match and strlen($match[0]) returns the length of the match; otherwise the expression will return 0.