How can I get a string that contains a-zA-Z0-9-=&_. and not get a string 0-9
Example php:
$text1 = "2017";
$text2 ="php 2017";
Example function:
function allow($str) {
if (preg_match("/[^a-zA-Z0-9\-=&_.]+/",$str)) {
return $str;
}else{
return false;
}
return $str;
}
like example
text 1 <- false.
text2 <- true.
Try this;
function allow($str) {
if (preg_match("/^[0-9]+$/", $str)) {
return false;
}
return true;
}
What about if $str equals to ""? This function returns true for "".
Edit: is_numeric may be faster than regular expression.
function allow($str) {
if (is_numeric($str)) {
return false;
}
return true;
}
Related
I need a regular expression to find out whether the string prefix to the number (_number) and if there is to get this number
//Valid
if (preg_match('/^([a-zA-Z0-9_])+([_])+([0-9]).html$/i', 'this_is_page_15.html'))
{
$page = 15;
}
//Invalid
if (preg_match('/^([a-zA-Z0-9_])+([_])+([0-9]).html$/i', 'this_is_page15.html')) // return false;
If I'm understanding you correctly, you would probably want some kind of function to do this. preg_match will return a 1 if it finds a match, a 0 if no match is found, and FALSE if there is an error. You need to supply the 3rd parameter $matches to capture the matched strings (details here: http://php.net/manual/en/function.preg-match.php).
function testString($string) {
if (preg_match("/^\w+_(\d+)\.html/",$string,$matches)){
return $matches[1];
} else {
return false;
}
}
So testString('this_is_page_15.html') will return 15, and testString('this_is_page15.html') will return FALSE.
$str = 'this_is_page_15.html';
$page;
if(preg_match('!_\d+!', $str, $match)){
$page = ltrim($match[0], "_");
}else{
$page = null;
}
echo $page;
//output = 15
I tried to look on here as to why this code is not working, got no where and now I'm hoping someone can help me out.
function validateData($string) {
if (empty($string)) {
return 'error';
} elseif (strlen($string) <= 1) {
return 'error';
} elseif (preg_match('[a-zA-Z0-9]+\ ?', $string)) {
return 'error';
} else {
return 'normal';
}
}
When I execute the above code, using:
echo validateData('Test');
echo validateData('Test!');
These both echo 'normal'.. however, the second example contains the '!' in the string and should return 'error' because of the preg_match statement in the above code.
Achievement Objective. Check a string to make sure that it is not EMPTY, that it is longer than 1 character and only contains a-z, A-Z, 0-9 or a space. So no special characters.
Thank you very much in advance to all answers, I really appreciate it!
Ken
Your pattern should look like this:
preg_match('/([^a-zA-Z0-9 ])+/', $string);
The ^ symbol is used to negate a character set.
use !preg_match(pattern,$string), if you need to validate strings which contains spaces, then use following, otherwise, remove \s from preg_match pattern
function validateData($string) {
if (empty($string)) {
return 'error';
} elseif (strlen($string) <= 1) {
return 'error';
} elseif (!preg_match('/^[A-Za-z0-9\s]+$/', $string)) {
return 'error';
} else {
return 'normal';
}
}
If the string is empty, it will be equal to 0 when you ask for it's string length, therefore testing empty($string) is useless since it is covered by the second test.
Using a regex adds complexity without benefit here, there is a dedicated function to return true or false for alphanumeric string: ctype_alnum($string)
Your function can just be:
function validateData($string) {
return (strlen($string) <= 1 || !ctype_alnum($string)) ? 'error' : 'normal';
}
try:
preg_match('/[a-zA-Z0-9]+\ ?/', $string)
Replace
preg_match('[a-zA-Z0-9]+\ ?', $string)
with
preg_match('/[^a-zA-Z0-9]/', $string)
I'm sure this is an easy solution - I wrote found this endswith function and thought I'd try the array_walk function instead of testing each string separately. I'd assumed that the result of the array_walk function would be false but it returns 1...How do I get it to test all the strings and return false if it didn't find a match? Thanks
class {
function endsWith($value,$key,$haystack)
{
$length = strlen($value);
if ($length == 0) {
return true;
}
return (substr($haystack, -$length) === $value);
}
function thing()
{
$email = "should#returnfalse.info";
$arr = array("#test.net","#test.org.uk","#test.co.uk","#test.com");
echo array_walk($arr,array($this,"endsWith"),$email);
}
}
The return value of array_walk is not determined by whatever the callback does; it only informs you if walking the entire array was completed successfully.
You may want to look into a few alternatives.
This will return the number of matching elements and will also serve as a boolean test, but it will evaluate every element no matter what:
echo count(array_filter($arr,array($this,"endsWith")));
This will stop evaluating elements with endsWith as soon as a match is detected and will return true if there is a match, false otherwise:
$self = $this;
// cast to int because false is printed as the empty string
echo (int)array_reduce($arr,
function($result, $v) use ($email, $self) {
return $result || $self->endsWith($v, null, $email);
},
false);
Try this
class {
function thing()
{
$email = "should#returnfalse.info";
$arr = array("#test.net","#test.org.uk","#test.co.uk","#test.com");
foreach ($arr as $domain) {
$length = strlen($value);
if ($length != 0) {
if (substr($email, -$length) === $domain) { echo $domain; break; }
}
}
}
}
array_walk() just iterates over the elements of an array and returns true, if it was able to do it. (echo casts boolea true to a string '1') Have a look at array_recude()
$that = $this; // Cannot access $this directly before PHP 5.4
var_dump(
array_reduce (
$arr,
function($result, item) use ($email, $that) { return $result || $that->endsWith($item, null /* not used anyway */, $email);},
false
)
);
Additional $key is not used and useless in endsWith().
If you want to apply a function to all values and return a single result you should use array_reduce.
As of PHP 5.3, you can use anonymous functions:
class {
function thing()
{
$email = "should#returnfalse.info";
$arr = array("#test.net","#test.org.uk","#test.co.uk","#test.com");
$match = '';
$found = false;
array_walk($arr,function($value) use (&$match, &$found, $email) {
$length = strlen($value);
if ($length == 0) {
$found = true;
return;
}
if (substr($email, -$length) === $value) {
$match = $value;
$found = true;
}
});
if ($found) {
echo 'Found match: ' . $match;
} else {
echo 'No match found :(';
}
}
}
I want to create a function in PHP that will return true when it finds that in the string there are some bad words.
Here is an example:
function stopWords($string, $stopwords) {
if(the words in the stopwords variable are found in the string) {
return true;
}else{
return false;
}
Please assume that $stopwords variable is an array of values, like:
$stopwords = array('fuc', 'dic', 'pus');
How can I do that?
Thanks
Use the strpos function.
// the function assumes the $stopwords to be an array of strings that each represent a
// word that should not be in $string
function stopWords($string, $stopwords)
{
// input parameters validation excluded for brevity..
// take each of the words in the $stopwords array
foreach($stopwords as $badWord)
{
// if the $badWord is found in the $string the strpos will return non-FALSE
if(strpos($string, $badWord) !== FALSE))
return TRUE;
}
// if the function hasn't returned TRUE yet it must be that no bad words were found
return FALSE;
}
Use regular expressions:
\b matches a word boundary, use it to match only whole words
use flag i to perform case-insensitive matches
Match each word like so:
function stopWords($string, $stopwords) {
foreach ($stopwords as $stopword) {
$pattern = '/\b' . $stopword . '\b/i';
if (preg_match($pattern, $string)) {
return true;
}
}
return false;
}
$stopwords = array('fuc', 'dic', 'pus');
$bad = stopWords('confucius', $stopwords); // true
$bad = stopWords('what the Fuc?', $stopwords); // false
A shorter version, inspired by an answer to this question: determine if a string contains one of a set of words in an array is to use implode to create one big expression:
function stopWords($string, $stopwords) {
$pattern = '/\b(' . implode('|', $stopwords) . ')\b/i';
return preg_match($pattern, $string) > 0;
}
function stopWords($string, $stopwords) {
$words=explode(' ', $string); //splits the string into words and stores it in an array
foreach($stopwords as $stopword)//loops through the stop words array
{
if(in_array($stopword, $words)) {//if the current stop word exists
//in the words contained in $string then exit the function
//immediately and return true
return true;
}
}
//else if none of the stop words were in $string then return false
return false;
}
I'm assuming here that $stopwords is an array to begin with. It should be if it's not.
Can someone help me with algorithm for finding the position of the first occurrence of any number in a string?
The code I found on the web does not work:
function my_offset($text){
preg_match('/^[^\-]*-\D*/', $text, $m);
return strlen($m[0]);
}
echo my_offset('[HorribleSubs] Bleach - 311 [720p].mkv');
The built-in PHP function strcspn() will do the same as the function in Stanislav Shabalin's answer when used like so:
strcspn( $str , '0123456789' )
Examples:
echo strcspn( 'That will be $2.95 with a coupon.' , '0123456789' ); // 14
echo strcspn( '12 people said yes' , '0123456789' ); // 0
echo strcspn( 'You are number one!' , '0123456789' ); // 19
HTH
function my_offset($text) {
preg_match('/\d/', $text, $m, PREG_OFFSET_CAPTURE);
if (sizeof($m))
return $m[0][1]; // 24 in your example
// return anything you need for the case when there's no numbers in the string
return strlen($text);
}
function my_ofset($text){
preg_match('/^\D*(?=\d)/', $text, $m);
return isset($m[0]) ? strlen($m[0]) : false;
}
should work for this. The original code required a - to come before the first number, perhaps that was the problem?
I can do regular expressions but I have to go into an altered state to
remember what it does after I've coded it.
Here is a simple PHP function you can use...
function findFirstNum($myString) {
$slength = strlen($myString);
for ($index = 0; $index < $slength; $index++)
{
$char = substr($myString, $index, 1);
if (is_numeric($char))
{
return $index;
}
}
return 0; //no numbers found
}
Problem
Find the first occurring number in a string
Solution
Here is a non regex solution in javascript
var findFirstNum = function(str) {
let i = 0;
let result = "";
let value;
while (i<str.length) {
if(!isNaN(parseInt(str[i]))) {
if (str[i-1] === "-") {
result = "-";
}
while (!isNaN(parseInt(str[i])) && i<str.length) {
result = result + str[i];
i++;
}
break;
}
i++;
}
return parseInt(result);
};
Example Input
findFirstNum("words and -987 555");
Output
-987