preg_match to check if string has specific structure - php

How can I check with php with preg_match() if string has specific structure. For example string is:
options:blue;white;yellow;
I want to check if string starts with string followed by : followed by n-numbers of strings separated by ;
And something which is important - string may be in Cyrillic, not only latin letters

Assuming only the restrictions listed in your question are needed, this will validate the string:
$number = 3;
$regex = sprintf('/^[^:]+:(?:[^;]+;){%d}$/', $number);
if (preg_match($regex, $string)) {
echo "It matches!";
} else {
echo "It doesn't match!";
}
Here's an example of it in action, using php -a:
php > $number = 3;
php > $regex = sprintf('/^[^:]+:(?:[^;]+;){%d}$/', $number);
php > if (preg_match($regex, 'options:blue;white;yellow;')) {
php { echo "It matches!";
php { } else {
php { echo "It doesn't match!";
php { }
It matches!
php > if (preg_match($regex, 'options:blue;white;yellow;green;')) {
php { echo "It matches!";
php { } else {
php { echo "It doesn't match!";
php { }
It doesn't match!
You can visualize this regex here. Let's break it down:
/.../ Start and end of the pattern.
^ Start of the string.
[^:]+ At least one character that is not a ':'.
: A literal ':'.
(?:[^;]+;){N} Exactly N occurrences of:
[^;]+ At least one character that is not a ';'.
; A literal ';'.
$ End of the string.

Related

Combining two conditions: Vowel and a space

I am trying to check for two conditions,
The string should contain a vowel.
The string should contain a space.
Here is what I am writing:
$reg = "/(?=.*(\s)) (?=.*(a|e|i|o|u))/";
But on running:
if ( preg_match($reg,"kka "))
echo "YES.";
else
echo "NO.";
I am getting NO. What am I doing wrong?
((?:.*)[aeiouAEIOU]+(?:.*)[ ]+(?:.*))|(?:.*)[ ]+((?:.*)[aeiouAEIOU]+(?:.*))
You can try with this
Explnation
Here is the correct way to use lookaheads:
^((?=.*\s.*).)((?=.*[aeiou].*).).*$
Demo here:
Regex101
If you want an option which does not involve using a regex would be to remove spaces/vowels from the input string and verify that the resulting length has decreased.
$input = "kka ";
if (strlen(preg_replace("/\s/", "", $input)) < strlen($input) &&
strlen(preg_replace("/[aeiouAEIOU]/", "", $input)) < strlen($input)) {
echo "both conditions satisfied"
else {
echo "both conditions not satisfied"
}
The alternative solution using preg_replace and strpos functions:
$str = " aa k";
if (($replaced = preg_replace("/[^aeiou ]/i", "", $str)) && strlen($replaced) >= 2
&& strpos($replaced, " ") !== false) {
echo 'Yes';
} else {
echo 'No';
}

How to return the special character found in string using PHP

I want to get the special chars found in string using PHP code, Here is my trial code:
$page_num =">256";
if(preg_match('^[-<>]+$', $page_num))
{
//Here it should returns special chars present in string..
}
check this
$page_num =">256";
if(preg_match_all('/\W/', $page_num,$matches))
{
print_r($matches);
}
What you have missed is ending delimiter
$page_num =">256";
if(preg_match('^[-<>]+$^', $page_num))
^// this one
{
//Here it should returns special chars present in string..
}
Demo of your code, here
or you can try this,
$string = 'your string here';
if (preg_match('/[\'^£$%&*()}{##~?><>,|=_+¬-]/', $string))
{
echo "yes";
} else {
echo "no";
}
One more solution is
preg_match('![^a-z0-9]!i', $string);

How to use wildcards in strpos

I have the below script which is working. I am looking for the string '1/72'
I would also like to look for the string '1:72' and '1\72' - how would I go about doing this easily (apart from just using multiple if statements?)
$string="test string 1/72 PHP";
if (strpos($string, '1/72') > 0) {
print "Got match!\n";
} else {
print "no match\n";
}
Use preg_match function.
if (preg_match("~1[\\\\:/]72~", $str)) {
[\\\\:/] character class which matches a backslash or : or forward slash.
DEMO
The fnmatch() function also provides a simple way to use pattern matching with shell wildcard expressions
$string="test string 1/72 PHP";
if (fnmatch('*1[/:\\\\]72*', $string)) {
print "Got match!\n";
} else {
print "no match\n";
}

Preg Match a string with $, numbers, and letters

I'm trying to preg_match this string.
$word = "$1$s";
or
$word = "$2$s"
if(preg_match('/^\$[1-9]{1}\$s$/' ,$word)){
echo 'true';
} else {
echo 'false';
}
I tried this but it is not giving a true result.
How can I make this true.
PHP is trying to render the variable $s in the double quoted string. Use single quotes instead and you can remove the {1} inside your regular expression because it is not necessary.
$word = '$1$s';
if (preg_match('/^\$[1-9]\$s$/', $word)) {
echo 'true';
} else {
echo 'false';
}
You can also escape the $ in your double quoted string:
$word = "$1\$s";
// Note $1 doesn't need to be escaped since variables can't start with numbers
Finally, you can see why this wasn't working by seeing what your $word actually equaled (with error reporting enabled):
$word = "$1$s"; // Notice: Undefined variable: s on line #
echo $word; // $1
Try this:
if(preg_match('/\$[1-9]{1}\$s/',$word)){
echo 'true';
} else {
echo 'false';
}

What is the correct return type of strpos? Searching for the '#' char

For example I have a string I am # the penthouse.
I need to know how to find the character "#" in php string and the position of the character.
I tried strpos but its not working.
Thanks for the help in advance.
EDIT:
I've been using this for get the character:
$text = "I am # the penthouse";
$pos = strrpos($text, '#');
if($pos == true)
{
echo "yes";
}
I would do this
Note, I'm using strpos, not reverse counterpart, strrpos
if (($pos = strpos('I am # the penthouse.', '#') !== false) {
echo "pos found: {$pos}";
}
else {
echo "no # found";
}
Note: Because # could be the first character in a string, strpos could return a 0. Consider the following:
// check twitter name for #
if (strpos('#twitter', '#')) { ... }
// resolves to
if (0) {
// this will never run!
}
So, strpos will explicitly return false when no match is found. This is how to properly check for a substring position:
// check twitter name for #
if (strpos('#twitter', '#') !== false) {
// valid twitter name
}
You can also use the function strpos() for that purpose. Like strrpos() it searches for a substring - or at least a char - in a string but it the returns the first position of that substring or boolean(false) if the substring was not found. So the snippet would look like:
$position = strpos('I am # the penthouse', '#');
if($position === FALSE) {
echo 'The # was not found';
} else {
echo 'The # was found at position ' . $position;
}
Note that there are common pitfalls that come with strpos() and strrpos() in php.
1 . Check Type of the return value!
Imagine the following example :
if(!strpos('#stackoverflow', '#')) {
echo 'the string contains no #';
}
The would output that '#' was not found although the string contains an '#'. Thats because of the weak data typing in PHP. The previous strpos() call will return int(0) because it is the first char in string. But unless you enforce a strict type check using the '===' operator this int(0) will be handle as FALSE. This is the correct way:
if(strpos('#stackoverflow', '#') === FALSE) {
echo 'the string contains no #';
}
2 . Use the correct order of arguments!
The signature of strpos is:
strpos($haystack, $needle [, $start]);
Thats unlike other str* functions in PHP where the $needle is the first arg.
Keep this in mind! ;)
This seems to be working for me in PHP 5.4.7:
$pos = strpos('I am # the penthouse', '#');
What do you mean exactly by strpos is not working?
Look this is working for me, it will also work for you
$string = "hello i am # your home";
echo strpos($string,"#");
i hope this will help -
<?php
$string = "I am # the penthouse";
$desired_char = "#";
// checking whether # present or not
if(strstr($string, $desired_char)){
// the position of the character
$position = strpos('I am # the penthouse', $desired_char);
echo $position;
}
else echo $desired_char." Not found!";
?>

Categories