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]);
}
Related
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 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
// ...
}
How does one replace all uppercase letters with a dash and lowercase equivalent in php?
Such as understandRegexBetter to understand-regex-better?
My Google-fu and experimentation with the following code hasn't gotten me very far.
echo preg_replace('/[A-Z]+/', "-$'", "understandRegexBetter");
Edit:
I forgot to specifically state that the first character is never uppercase.
Preferred Method:
This method replaces any set of capital letters preceded by a lowercase letter with a - and the set of capital letters. Then we lowercase the whole string after the fact.
echo strtolower(preg_replace(
'/(?<=[a-z])([A-Z]+)/',
'-$1',
'understandRegexBetter'
));
RegEx Callback:
Uses preg_replace_callback() to replace any set of capital letters with a - followed by the letters passed through strtolower(). This, however, will leave a preceding - in your string (we could look for a preceding characters in the RegEx, but then your first letter would be left uppercase).
echo preg_replace_callback(
'/[A-Z]+/',
function ($matches) {
$character = reset($matches);
return '-' . strtolower($character);
},
'understandRegexBetter'
);
Deprecated:
Side note, you can technically use preg_replace() with the e modifier but it is deprecated as of PHP 5.5. An example would be:
echo preg_replace(
'/([A-Z]+)/e',
'"-" . strtolower("$1")',
'understandRegexBetter'
);
You can do this:
echo strtolower(preg_replace('~(?=[A-Z])(?!\A)~', '-', $str));
try this:
echo strtolower(preg_replace('/([A-Z]+)/', "-$1", "understandRegexBetter"));
You can use:
$s = 'understandRegexBetter';
$r = preg_replace_callback('~(?<=[a-z])([A-Z])~',
function ($m) { return '-' . strtolower($m[1]); }, $s);
echo $r;
You could try something like this (e flag means evaluate):
echo preg_replace('/([A-Z])/e', "strtolower('-\\1')", "understandRegexBetter");
I need a regular expression to check a string for uppercase letters. Where It finds a uppercase It needs to add white space before it. I write some code for this, but the problem is that it only works if there is only one uppercase letter in the string. But I need to work with any number of uppercase letter exists in the string. I pasted my code below:
$regEx = preg_match('*[A-Z]*', $str, $matches, PREG_OFFSET_CAPTURE);
if(!empty($regEx)) {
$str = substr_replace($str,' ', $matches[0][1], 0);
}
I need a regular expression to check a string for uppercase letters. Where it finds a uppercase, it needs to add white space before it.
preg_replace() sounds a more suitable candidate to achieve this...
$str = preg_replace('/[A-Z]/', ' $0', $str);
CodePad.
Please try below code:
if(preg_match("/[A-Z]/", $string)===0) {
return true;
}
I know that there is the function ctype_alpha, though this one will return FALSE when the string contains spaces (white space character).
How do I allow alpha characters and spaces, but nothing else?
$is_alpha_space = ctype_alpha(str_replace(' ', '', $input)));
or
$is_alpha_space = preg_match('/^[a-z\s]*$/i', $input);
if (preg_match("^/[a-zA-Z ]+$/", $input)) {
// input matches
}
Demo: http://ideone.com/jp6Wi
Docs: http://php.net/manual/en/function.preg-match.php
ctype_alpha(preg_replace('/\s/', '', $mystring))
The inner expression returns the string without spaces, and then you use ctype_alpha`` as you wish
Removing the spaces is the way to go, but remember ctype_alpha results in a false on an empty string these days! Below the method I use...
function validateAlpha($valueToValidate, $spaceAllowed = false) {
if ($spaceAllowed) {
$valueToValidate = str_replace(' ', '', $valueToValidate);
}
if (strlen($valueToValidate) == 0) {
return true;
}
return ctype_alpha($valueToValidate);
}
I would work around with a Simple regex and with the php function preg_match() like this:
if(preg_match("/^[a-zA-Z ]+$/", $varToCheck)){
//your code here
}
The important part here is the regex that identifies the parts you want, in my case I wanted text for a name field and with spaces like the case in here.[a-z] is the range from a to z, A-Z are the range from A to Z and the " " at the end represents the spaces.
Hope this helps someone.