PHP preg_match for only numbers and letters, no special characters - php

I don't want preg_match_all ... because the form field only allows for numbers and letters... just wondering what the right syntax is...
Nothing fancy ... just need to know the right syntax for a preg_match statement that looks for only numbers and letters. Something like
preg_match('/^([^.]+)\.([^.]+)\.com$/', $unit)
But that doesn't look for numbers too....

If you just want to ensure a string contains only alphanumeric characters. A-Z, a-z, 0-9 you don't need to use regular expressions.
Use ctype_alnum()
Example from the documentation:
<?php
$strings = array('AbCd1zyZ9', 'foo!#$bar');
foreach ($strings as $testcase) {
if (ctype_alnum($testcase)) {
echo "The string $testcase consists of all letters or digits.\n";
} else {
echo "The string $testcase does not consist of all letters or digits.\n";
}
}
?>
The above example will output:
The string AbCd1zyZ9 consists of all letters or digits.
The string foo!#$bar does not consist of all letters or digits.

if(preg_match("/[A-Za-z0-9]+/", $content) == TRUE){
} else {
}

If you want to match more than 1, then you'll need to, however, provide us with some code and we can help better.
although, in the meantime:
preg_match("/([a-zA-Z0-9])/", $formContent, $result);
print_r($result);
:)

Related

How to change specific first Letter in string to Capital using PHP?

If the first character of my string contains any of the following letters, then I would like to change the first letter to Uppercase: (a,b,c,d,f,g,h,j,k,l,m,n,o,p,q,r,s,t,v,w,y,z) but not (e,i,u,x).
For example,
luke would become Luke
egg would stay the same as egg
dragon would become Dragon
I am trying to acheive this with PHP, here's what I have so far:
<?php if($str("t","t"))
echo ucfirst($str);
else
echo "False";
?>
My code is simply wrong and it doesn't work and I would be really grateful for some help.
Without regex:
function ucfirstWithCond($str){
$exclude = array('e','i','u','x');
if(!in_array(substr($str, 0, 1), $exclude)){
return ucfirst($str);
}
return $str;
}
$test = "egg";
var_dump(ucfirstWithCond($test)); //egg
$test = "luke";
var_dump(ucfirstWithCond($test)); //Luke
Demo:
http://sandbox.onlinephpfunctions.com/code/c87c6cbf8c616dd76fe69b8f081a1fbf61cf2148
You may use
$str = preg_replace_callback('~^(?![eiux])[a-z]~', function($m) {
return ucfirst($m[0]);
}, $str);
See the PHP demo
The ^(?![eiux])[a-z] regex matches any lowercase ASCII char at the start of the string but e, u, i and x and the letter matched is turned to upper inside the callback function to preg_replace_callback.
If you plan to process each word in a string you need to replace ^ with \b, or - to support hyphenated words - with \b(?<!-) or even with (?<!\S) (to require a space or start of string before the word).
If the first character could be other than a letter then check with an array range from a-z that excludes e,i,u,x:
if(in_array($str[0], array_diff(range('a','z'), ['e','i','u','x']))) {
$str[0] = ucfirst($str[0]);
}
Probably simpler to just check for the excluded characters:
if(!in_array($str[0], ['e','i','u','x'])) {
$str[0] = ucfirst($str[0]);
}

PHP preg_replace help trim special characters

I tried to search around but couldn't find anything useful. I need to trim special characters from beginning and end of a string and identify if the remaining portion is a number.
For example
(5)
[[12]]
{3}
#!8(#
!255=
/879/
I need a preg_match expression for it. The regular expression should ignore the string if any alphabets come in between.
$string="yourstring";
$new_string=preg_replace('/[^A-Za-z0-9]/', '', $string);
if(is_numeric($new_string){
echo "number";
} else {
echo "string";
}
^(?!.*[a-zA-Z])\W*(\d+)\W*$
You can use this.Lookahead will validate if only numbers are there.Replace by $1.See demo.
https://regex101.com/r/cT0hV4/2

PHP uppercase letter in String

Like the title says, I'm looking for a way to check if a string contains an uppercase letter in it. It is for a password field, and I cannot use regex because we have not learned any of that yet in class.
I tried to use ctype_upper but that only seems to work if every character in the string is uppercase.
Is there a way to check any character in a string, but not using regex?
You can try this:
if (strtolower($string) != $string) {
echo 'You have uppercase in your string';
} else {
echo 'You have no uppercase in your string';
}
This checks if the converted string to lowercase is equal to the original string. Hope this helps...
Try this..
Use the strtoupper() function to transform the string into all uppercase characters that’s capitalized letters, and then compare the transformed string against the original one to see if they are identical. If they are, then you are pretty sure the original string was also a string consisting of ONLY capital letters
if (strtoupper($string) == $string) {
echo $string.' is all uppercase letters.';}
function isPartUppercase($string) { if(preg_match("/[A-Z]/", $string)===0) { return true; } return false; }
The function uses a simple regular expression that tries to find any upper case A-Z characters, preg_match() returns the number of instances of the expression it finds in the string, but stops at 1, preg_match_all() returns the count of all instances it finds.

PHP: str_word_count(åäöåäöåäöåäö) returns the integer value of 12

I am using special symbols such as å ä ö on my website which measures the lengths of different texts. Thing is, I have noticed that PHP counts the symbols "å" "ä" "ö" as 1 word each. So åäö counts as 3 words, and åäöåäöåäöåäöåäö counts as 15 words. Well this is clearly not correct and I cannot find an answer to this problem anywhere. I'd be thankful for a useful answer, thank you!
If there's a limited set of word characters that you need to take into account, just supply those into str_word_count with its third param (charlist):
$charlist = 'åäö';
echo str_word_count('åäöåäöåäöåäöåäö', 0, $charlist); // 1
Alternatively, you can write your own Unicode-ready str_word_count function. One possible approach is splitting the source string by non-word symbols, then counting the resulting array:
function mb_str_word_count($str) {
return preg_match_all('#[\p{L}\p{N}][\p{L}\p{N}\'-]*#u', $str);
}
Basically, this function counts all the substrings in the target string that start with either Letter or Number character, followed by any number (incl. zero) of Letters, Numbers, hyphens and single quote symbols (matching the description given in str_word_count() docs).
You can try adding
setlocale(LC_ALL, 'en_US.utf8')
before your call to str_word_count
or roll on your own with
substr_count(trim($str), ' ');
this work for me... hope its usefull.
USING str_word_count you need to use utf8_decode(utf8_encode)..
function cortar($str)
{
if (20>$count=str_word_count($str)) {
return $str;
}
else
{
$array = str_word_count($str,1,'.,-0123456789()+=?¿!"<>*ñÑáéíóúÁÉÍÓÚ#|/%$#¡');
$s='';
$c=0;
foreach ($array as $e) {
if (20>$c) {
if (19>$c) {
$s.=$e.' ';
}
else
{
$s.=$e;
}
}
$c+=1;
}
return utf8_decode(utf8_encode($s));
}
}
function returs 20 words
If it is a string without linebreaks, and words are separated by a whitespace, a simple workaround would be to trim() the string and then count the whitespaces.
$string = "Wörk has to be done.";
// 1 space is 2 words, 2 spaces are 3 words etc.
if(substr_count(trim($string), ' ') > 2)
{
// more than 3 words
// ...
}

What's a regular expression for a certain ruleset in PHP?

Specifically, it should be 6 or more alphanumerics (0-9 + a-z).
The second character is a letter.
The third character is an odd number.
Any help?
An example regex that matches this for ASCII is
^[0-9A-Za-z][A-Za-z][13579][0-9A-Za-z]{3,}$
PHP code
<?php
$test = '0A1000';
if (preg_match('/^[0-9A-Za-z][A-Za-z][13579][0-9A-Za-z]{3,}$/', $test)) {
// Do some stuff
echo "matched";
}

Categories