what regex would be used to search for an asterisk followed by a space followed by an equlas sign?
that is '* =' ?
Using preg_match in php would find a match in these strings:
'yet again * = it happens'
'again* =it happens'
and what is simplest way to search for an exact word for word, number for number, puncuation sign for puncuation sign string in regex?
You don't need a regular expression here. Consider using strpos
$pos = strpos('yet again * = it happens', '* =');
if(pos === false){
// not there
}
else {
// found
}
If you must use preg_match, remember the delimiters:
preg_match('/\* =/', $str, $matches);
In this case you have to escape the asterisk. You may want to allow more spaces, for example with the pattern \*\h+=. \h stands for horizontal whitespace characters.
Try this regex pattern
\*(?=\s=)
<?php
function runme($txt) {
return preg_match("/^\*\ \=$/", $txt);
}
echo runme($argv[1])? "$argv[1] matches!\n" : "$argv[1] is not asterisk space equals-sign\n";
?>
$ php asterisk_space_equals.php 'yet again * = it happens'
yet again * = it happens is not asterisk space equals-sign
$ php asterisk_space_equals.php 'again* =it happens'
again* =it happens is not asterisk space equals-sign
$ php asterisk_space_equals.php '* ='
* = matches!
Related
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;
}
How to check below line in regular expression?
[albums album_id='41']
All are static except my album_id. This may be 41 or else.
Below my code I have tried but that one not working:
$str = "[albums album_id='41']";
$regex = '/^[albums album_id=\'[0-9]\']$/';
if (preg_match($regex, $str)) {
echo $str . " is a valid album ID.";
} else {
echo $str . " is an invalid ablum ID. Please try again.";
}
Thank you
You need to escape the first [ and add + quantifier to [0-9]. The first [ being unescaped created a character class - [albums album_id=\'[0-9] and that is something you did not expect.
Use
$regex = '/^\[albums album_id=\'[0-9]+\']$/';
Pattern details:
^ - start of string
\[ - a literal [
albums album_id=\'- a literal string albums album_id='
[0-9]+ - one or more digits (thanks to the + quantifier, if there can be no digits here, use * quantifier)
\'] - a literal string ']
$ - end of string.
See PHP demo:
$str = "[albums album_id='41']";
$regex = '/^\[albums album_id=\'[0-9]+\']$/';
if (preg_match($regex, $str)) {
echo $str . " is a valid album ID.";
} else {
echo $str . " is an invalid ablum ID. Please try again.";
}
// => [albums album_id='41'] is a valid album ID.
You have an error in your regex code, use this :
$regex = '/^[albums album_id=\'[0-9]+\']$/'
The + after [0-9] is to tell that you need to have one or more number between 0 and 9 (you can put * instead if you want zero or more)
To test your regex before using it in your code you can work with this website regex101
I need to check to see if a variable contains anything OTHER than 0-9 and the "-" and the "+" character and the " "(space).
The preg_match I have written does not work. Any help would be appreciated.
<?php
$var="+91 9766554433";
if(preg_match('/[0-9 +\-]/i', $var))
echo $var;
?>
You have to add a * as a quantifier to the whole character class and add anchors to the start and end of the regex: ^ and $ means to match only lines containing nothing but the inner regex from from start to end of line. Also, the i modifier is unnecessary since there is no need for case-insensitivity in this regex.
This should do the work.
if(!preg_match('/^[0-9 +-]*$/', $var)){
//variable contains char not allowed
}else{
//variable only contains allowed chars
}
Just negate the character class:
if ( preg_match('/[^0-9 +-]/', $var) )
echo $var;
or add anchors and quantifier:
if ( preg_match('/^[0-9 +-]+$/', $var) )
echo $var;
The case insensitive modifier is not mandatory in your case.
You can try regex101.com to test your regex to match your criteria and then on the left panel, you'll find code generator, which will generate code for PHP, Python, and Javascript.
$re = "/^[\\d\\s\\+\\-]+$/i";
$str = "+91 9766554433";
preg_match($re, $str, $matches);
You can take a look here.
Try see if this works. I haven't gotten around to test it beforehand, so I apologize if it doesn't work.
if(!preg_match('/^[0-9]+.-.+." ".*$/', $var)){
//variable contains char not allowed
}else{
//variable only contains allowed chars
}
I have a variable I want to use in a preg_match combined with some regex:
$string = "cheese-123-asdf";
$find = "cheese";
if(preg_match("/$find-/d.*/", $string)) {
echo "matched";
}
In my pattern I am trying to match using cheese, followed by a - and 1 digit, followed by anything else.
change /d to \d
there is no need to use .*
if your string is defined by user (or may contains some characters (e.g: / or * or ...)) this may cause problem on your match.
Code:
<?php
$string = "cheese-123-asdf";
$find = "cheese";
if(preg_match("/$find-\d/", $string))
{
echo "matched";
}
?>
You mistyped / for \:
if(preg_match("/$find-\d.*/", $string)) {
The .* is also not really necessary since the pattern will match either way.
for digit, it's \d
if(preg_match("/$find-\d.*/", $string)) {
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