I want to check if a string contains a character repeated zero or more times, for example:
If my string is aaaaaa, bbbb, c or ***** it must return true.
If it contains aaab, cd, or **%*** it must return false.
In other words, if the string has 2 or more unique characters, it must return false.
How to go about this in PHP?
PS: Is there a way to do it without RegEx?
You could split on every character then count the array for unique values.
if(count(array_count_values(str_split('abaaaa'))) == 1) {
echo 'True';
} else {
echo 'false';
}
Demo: https://eval.in/760293
count(array_unique(explode('', string)) == 1) ? true : false;
You can use a regular expression with a back-reference:
if (preg_match('/^(.)\1*$/', $string)) {
echo "Same characters";
}
Or a simple loop:
$same = true;
$firstchar = $string[0];
for ($i = 1; $i < strlen($string); $i++) {
if ($string[$i] != $firstchar) {
$same = false;
break;
}
}
For the fun of it:
<?php
function str2Dec($string) {
$hexstr = unpack('H*', $string);
$hex = array_shift($hexstr);
return hexdec($hex);
}
function isBoring($string) {
return str2Dec($string) % str2Dec(substr($string, 0, 1)) === 0;
}
$string1 = 'tttttt';
$string2 = 'ttattt';
var_dump(isBoring($string1)); // => true
var_dump(isBoring($string2)); // => false
Obviously this works only in small strings because once it gets big enough, the INT will overflow and the mod will not produce the correct value. So, don't use this :) - posting it just to show a different idea from the usual ones.
strlen(str_replace($string[0], '', $string)) ? false : true;
You can check that the number of unique characters is greater than 1. This will perform well even if the input string is empty: (Demo)
$string = 'aaaba';
var_export(
strlen(count_chars($string, 3)) < 2 // false
);
Alternatively, you can trim the string by its first character, but this will generate warnings/notices if the input string has no length. (Demo)
$string = 'aaaba';
var_export(
!strlen(trim($string, $string[0])) // false
);
p.s. Yes, you could use !strlen(trim($string, #$string[0])) to prevent warnings/notices caused by a zero-length string, but I avoid error suppression like the plague because it generally gives code a bad smell.
Regex: ^(.)\1{1,}
^: Starting of string
(.): Match and capture single characted.
\1{1,}: using captured character one or more than once.
For this you can use regex
OR:
PHP code demo
$string="bbbb";
if($length=strlen($string))
{
substr_count($string,$string[0]);
if($length==substr_count($string,$string[0]))
{
echo "Do something";
}
}
Related
I have a string that contains 2 informations (1.A Boolean/2.Something(could be number, letter, special chars and could be of any length)).
2 is a user input.
Exemples:
(part 1)"true".(part 2)"321654987" => "true321654987"
Could also be
"false321654987" or "trueweiufv2345fewv"
What I need is a way of parsing trought the string to check first if 1 is true (if its false do nothing), if it is true I need to check if to following part is a positive number higher than 0 (must accepte any number higher than 0 even decimal BUT not bin or hex (well... could be 10 but its would mean ten not two)).
Here is what I tried:
//This part is'nt important it work as it should....
if(isset($_POST['validate']) && $_POST['validate'] == "divSystemePositionnement")
{
$array = json_decode($_POST['array'], true);
foreach($array as $key=>$value)
{
switch($key)
{
case "txtFSPLongRuban":
//This is the important stuff HERE.....
if(preg_match('#^false.*$#', $value))//If false do nothing
{}
else if(!preg_match('#^true[1-9][0-9]*$#', $value))//Check if true and if number higher than 0.
{
//Do stuff,
//Some more stuff
//Just a bit more stuff...
//Done! No more stuff to do.
}
break;
//Many more cases...
}
}
}
As you can see I use regEx to parse trought to string. But it does'nt match decimal number.
I know how to do a regEx to parse decimal this is'nt the question.
The question is:
is there already a function in php that match the parsing I need?
If not, do any of you know a more efficient way to do the parsing or should I just add to my regEx the decimal part?
I was thinking something like :
test = str_split($value, "true")
if(isNumeric(test[1]) && test[1] > 0)
//problem is that isNumeric accepte hex and a cant have letter in there only straight out int or decimal number higher than 0.
Any idea??
Thank you so much for the help!
Use substr : documentation
if(substr($value, 0, 4) == "true"){
$number_part = substr($value, 5);
if(((int) $number == $number) || ((float) $number == $number)){
//do something...
}
}
You can do this:
case "txtFSPLongRuban":
if (preg_match('~^true(?=.*[^0.])([0-9]+(?:\.[0-9]+)?)$~', $value, $match))
{
// do what you want with $match[1] that contains the not null number.
}
break;
The lookahead (?=.*[^0.]) checks if there is somewhere a character that is not a 0 or a .
This oughta do the trick, and handle both types of values:
preg_match('/^(true|false)(.*)$/', $value, $matches);
$real_val = $matches[2];
if ($matches[1] == 'true') {
... true stuff ...
} else if ($matches[1] == 'false') {
... false stuff ...
} else {
... file not found stuff ...
}
Have a try with:
else if(!preg_match('#^true([1-9][0-9]*(?:\.[0-9]*)?$#', $value))
Have a look at ctype_digit:
Checks if all of the characters in the provided string, text, are numerical.
To check for decimals you can use filter_var:
if (filter_var('123.45', FILTER_VALIDATE_FLOAT) !== false) {
echo 'Number';
}
I have two variables such as:
var1 = "z";
var2 = "A";
how can I check if var1 is after in the alphabet than var2 (in this case it should return true)?
I think everyone who has answered agrees that strcmp() is the right answer, but every answer provided so far will give you incorrect results. Example:
echo strcmp( "Z", "a" );
Result: -1
echo strcmp( "z", "A" );
Result: 1
strcmp() is comparing the binary (ord) position of each character, not the position in the alphabet, as you desire. If you want the correct results (and I assume that you do), you need to convert your strings to the same case before making the comparison. For example:
if( strcmp( strtolower( $str1 ), strtolower( $str2 ) ) < 0 )
{
echo "String 1 comes before string 2";
}
Edit: you can also use strcasecmp(), but I tend to avoid that because it exhibits behavior that I've not taken the time to understand on multi-byte strings. If you always use an all-Latin character set, it's probably fine.
What did you try?... pretty sure this works
<?php
if(strcmp($var1,$var2) > 0) {
return true;
}
If you're comparing a single character, you can use ord(string). Note that uppercase values compare as less than lowercase values, so convert the char to lowercase before doing the comparison.
function earlierInAlphabet($char1, $char2)
{
$char1 = strtolower($char1);
$char2 = strtolower($char2);
if(ord($char1) < ord($char2))
return true;
else
return false;
}
function laterInAlphabet($char1, $char2)
{
$char1 = strtolower($char1);
$char2 = strtolower($char2);
if(ord($char1) > ord($char2))
return true;
else
return false;
}
If you're comparing a string (or even a character) then you can also use strcasecmp(str1, str2):
if(strcasecmp($str1, $str2) > 0)
// str1 is later in the alphabet
return strcmp($var1,$var2) > 0?
You should use http://php.net/manual/en/function.strcmp.php
Returns < 0 if str1 is less than str2; > 0 if str1 is greater than str2, and 0 if they are equal.
So
return strcmp(var1, var2) > 0 // will return true if var1 is after var2
This solution may be over-the-top for just two variables; but this is for ever if you need to solve if a bunch of variables (2+) would be in the right order...
<?php
$var1='Z';
$var2='a';
$array1 = array();
$array[] = $var1;
$array1[] = $var2;
$array2 = sort($array1);
if($array2 === $array1){
return true;
}else{
return false;
}
?>
Other than that if you only want to do it with two variables this should work just fine.
<?php
return (strcmp($var1,$var2) > 0);
?>
I use this code in php to detect whether there is five same symbols in a row in the string and execute some code if it does.
function symbolsInRow($string, $limit = 5) {
$regex = '/(.)\1{'.($limit - 1).',}/us';
return 0 == preg_match($regex, $string);
}
Now I need to do the same thing in javascript, but unfortunately I'm not familiar with it enough. How can be this function converted into javascript? The function should return false if it finds 5 same symbols in row in the given string.
Here you go
function symbolsInRow(string, limit) {
// set the parameter to 5 if it is not provided
limit = (limit || 5);
// create a regexp object, initialized with the regex you want. we escape the \ with \\ because it is a special char in javascript strings.
var regex = new RegExp('(.)\\1{'+(limit-1)+',}');
// return false if we find a match (true if no match is found)
return !regex.test(string);
}
the actual test method will return true if it finds a match. So notice the ! which is the not operator inverting the result of the test, since you wanted to return false if it found a sequence.
example at http://www.jsfiddle.net/gaby/aPTAb/
May be not with a regexp:
function symbolsInRow(str, limit, symbol){
return str.split(symbol).length === limit + 1;
}
This should be equivalent:
function symbolsInRow(string, limit) {
limit = (limit || 5) - 1;
return !(new RegExp('(.)\\1{'+limit+'}')).test(string);
}
For five case-sensitive characters in a row, this should work:
function symbolsInRow(string) {
return /(.)\1{4}/.test(string);
}
If you need to match an arbitrary number of repetitions:
function symbolsInRow(string,limit) {
return (new RegExp('(.)\\1{'+limit+'}')).test(string);
}
I want to check if a variable has a number in it, I just want to see if there is one I don't care if it has any thing else in it like so:
"abc" - false
"!./#()" - false
"!./#()abc" - false
"123" - true
"abc123" - true
"!./#()123" - true
"abc !./#() 123" -true
There are easy ways of doing this if you want to know that is all numbers but not if it just has one. Thanks for your help.
You can use the strcspn function:
if (strcspn($_REQUEST['q'], '0123456789') != strlen($_REQUEST['q']))
echo "true";
else
echo "false";
strcspn returns the length of the part that does not contain any integers. We compare that with the string length, and if they differ, then there must have been an integer.
There is no need to invoke the regular expression engine for this.
$result = preg_match("/\\d/", $yourString) > 0;
Holding on to spirit of #Martin, I found a another function that works in similar fashion.
(strpbrk($var, '0123456789')
e.g. test case
<?php
function a($var) {
return (strcspn($var, '0123456789') != strlen($var));
}
function b($var) {
return (strpbrk($var, '0123456789'));
}
$var = array("abc", "!./#()", "!./#()abc", "123", "abc123", "!./#()123", "abc !./#() 123");
foreach ($var as $v) {
echo $v . ' = ' . b($v) .'<hr />';
}
?>
This should help you:
$numberOfNumbersFound = preg_match("/[0-9]+/", $yourString);
You could get more out of the preg_match function, so have a look at its manual
you can use this pattern to test your string using regular expressions:
$isNumeric = preg_match("/\S*\d+\S*/", $string) ? true : false;
In PHP 5, I use intval() whenever I get numbers as an input. This way, I want to ensure that I get no strings or floating numbers. My input numbers should all be in whole numbers. But when I get numbers >= 2147483647, the signed integer limit is crossed.
What can I do to have an intval() equivalent for numbers in all sizes?
Here's what I want to have:
<?php
$inputNumber = 3147483647.37;
$intNumber = intvalEquivalent($inputNumber);
echo $intNumber; // output: 3147483647
?>
Thank you very much in advance!
Edit: Based on some answers, I've tried to code an equivalent function. But it doesn't work exactly as intval() does yet. How can I improve it? What is wrong with it?
function intval2($text) {
$text = trim($text);
$result = ctype_digit($text);
if ($result == TRUE) {
return $text;
}
else {
$newText = sprintf('%.0f', $text);
$result = ctype_digit($newText);
if ($result == TRUE) {
return $newText;
}
else {
return 0;
}
}
}
Try this function, it will properly remove any decimal as intval does and remove any non-numeric characters.
<?php
function bigintval($value) {
$value = trim($value);
if (ctype_digit($value)) {
return $value;
}
$value = preg_replace("/[^0-9](.*)$/", '', $value);
if (ctype_digit($value)) {
return $value;
}
return 0;
}
// SOME TESTING
echo '"3147483647.37" : '.bigintval("3147483647.37")."<br />";
echo '"3498773982793749879873429874.30872974" : '.bigintval("3498773982793749879873429874.30872974")."<br />";
echo '"hi mom!" : '.bigintval("hi mom!")."<br />";
echo '"+0123.45e6" : '.bigintval("+0123.45e6")."<br />";
?>
Here is the produced output:
"3147483647.37" : 3147483647
"3498773982793749879873429874.30872974" : 3498773982793749879873429874
"hi mom!" : 0
"+0123.45e6" : 0
Hope that helps!
you can also use regular expressions to remove everything after the intial numeric parts:
<?php
$inputNumber = "3147483647.37";
$intNumber = preg_replace('/^([0-9]*).*$/', "\\1", $inputNumber);
echo $intNumber; // output: 3147483647
?>
Either use number_format($inputNumber, 0, '', '')
Or if you only want to check if its a whole number then use ctype_digit($inputNumber)
Don't use the proposed is_numeric, as also floats are numeric. e.g. "+0123.45e6" gets accepted by is_numeric
In addition to number_format, you can use sprintf:
sprintf("%.0f", 3147483647.37) // 3147483647
However, both solutions suffer from float overflow, for example:
sprintf("%.0f", 314734534534533454346483647.37) // 314734534534533440685998080
If you want to handle arbitrary-precision numbers, you will need to use the gmp extension. The function gmp_init(), for example, converts a string to a gmp resource object. the drawback is that you must use other functions of that extension to further process that object. Converting it back to a string is done using gmp_strval(), for example.
$gmpObject = gmp_init($string, 10);
if ($gmpObject === FALSE) {
# The string was not a valid number,
# handle this case here
}
echo gmp_strval($gmpObject);
You might want to only verify that the string is representing a valid number and use the string itself, if you do not intend to do any operations on the value. That can be done using a regular expression:
$containsInt = preg_match('/^\d+$/', $string);
# Or for floating point numbers:
$containsFloat = preg_match('/^\d+(.\d+)?$/', $string);
echo $string;
Another option is to use is_numeric(). But that function does more conversion than you might like. Quoting from docs of that function:
... +0123.45e6 is a valid numeric value ...
<?php
$a = 453453445435.4;
echo $bigint = floor($a);