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);
}
Related
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";
}
}
I have a simple function which checks if a value is a number and if that number is less than 0.
function check_number($value){
if(!is_numeric(strval($value))){
return "value must be whole or decimal";
} else {
if($value < 0){
return "value must be bigger than 0";
}
}
return "successful value";
}
This functions works all well and good, until special numbers are passed in such as:
0xf4c3b00c
1e7
These values will still make the function return "successful value".
How can I make these special numbers not return a false positive in my case.
Thanks.
function check_number($value){
if (!is_numeric($value)) {
return "That is not a number";
}
if ($value < 0) {
return "value must be bigger than 0";
}
if(!ctype_digit(str_replace('.', '', $value))){
return "value must be whole or decimal";
}
return "successful value";
}
SEE DEMO
You have peculiar requirements. Your definition of a number differs from PHP's - 4.1e7 is a number, just not one formatted in a way you like. So you need to look at the number as it appears - as a string.
Check if value is less than 0 first, because later we won't distinguish between a minus sign and any other character.
Count dots in the number string.
If more than 1 dot, return fail.
If just 1 dot, str_replace it out and continue.
Finally, use ctype_digit on the remaining string.
Change
if(!is_numeric(strval($value))){
into
$value = trim($value, "0"); // get value as string and remove leading and trailing zeroes
$value_float = ltrim(floatval($value), "0"); // get float value as string and remove leading zero
if($value !== $value_float){
or to make it compacter
if(trim($value, "0") !== ltrim(floatval($value), "0")){
to check whether the numerical representation is still the same after stringifying.
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';
}
If I have two PHP variables that are strings and one is a multi-word string while the other is a single-word string.
How can I write a custom function that returns true if the larger string contains the smaller string.
Here is what I have so far in terms of code:
function contains($smaller, $larger){
//if $smaller is in larger{
return true;
}
else{
return false;
}
How can I do the commented out part?
I can't use a regex since I don't know the exact value of $smaller, right?
This version should return a Boolean and guard against 0 vs false return
function contains($smaller, $larger){
return strpos($larger, $smaller) !== false;
}
There is a php function strstr which will return the position of the "smaller" string.
http://www.php.net/manual/en/function.strstr.php
if(strstr($smaller, $larger))
{
//Its true
}
PHP already has it. Strpos is your answer
http://php.net/manual/en/function.strrpos.php
if (strpos($larger, $smaller) !== false){
// smaller string is in larger
} else {
// does not contains
}
If it founds the string, it returns the position. Beware to check for 0 (if the position of a smaller is in the 0-th location)
I have a variable:
$testingAllDay = $event->when[0]->startTime;
This variable will be this format if it is "All Day":
2011-06-30
It will be this format if it is not "All Day":
2011-07-08T12:00:00.000-05:00
I'm wanting to do something like:
if ($testingAllDay does not contain "T"){
$AllDay = 1;
} else {
$AllDay = 0;
}
Do I need to use a strstr() here, or is there another function that does this? Thanks!
One option is to use strpos to see if the 'T' character is present in the string as follows:
if (strpos($testingAllDay, 'T') !== false) {
// 'T' was present in $testingAllDay
}
That said, it would probably be faster/more efficient (although no doubt meaninglessly so) to use strlen in this case, as according to your example, the time-free field will always be 10 characters long.
For example:
if(strlen($testingAllDay) > 10) {
// 'T' was present in $testingAllDay
}
Use strpos:
if (strpos($testingAllDay,"T")!==false){
or strstr
if (!strstr($testingAllDay,"T")){
if (strpos($testingAllDay, 'T') !== FALSE){
...
}
If those are the only possible cases, even strlen() will do.
not exactly answer to the question, but you could check with strlen().
i.e. "All Day" length is 10, anything above that is not.
The function you're looking for is strpos(). The following is an example picking up your wording for the variable names even:
$testingAllDayTPosition = strpos($testingAllDay, 'T');
$testingAllDayDoesNotContainT = false === $testingAllDayTPosition;
if ($testingAllDayDoesNotContainT){
$AllDay = 1;
} else {
$AllDay = 0;
}
strstr and strpos are two functions by which you can complete your requirement.
strstr will see if substring exists in string and it will echo from first occurrence of string to rest.
While strpos will give you position of first occurrence of the string.