i am trying to get a php if statement to have the rule where if a set variable equals "view-##" where the # signifies any number. what would be the correct syntax for setting up an if statement with that condition?
if($variable == <<regular expression>>){
$variable2 = 1;
}
else{
$variable2 = 2;
}
Use the preg_match() function:
if(preg_match("/^view-\d\d$/",$variable)) { .... }
[EDIT] OP asks additionally if he can isolate the numbers.
In this case, you need to (a) put brackets around the digits in the regex, and (b) add a third parameter to preg_match().
The third parameter returns the matches found by the regex. It will return an array of matches: element zero of the array will be the whole matched string (in your case, the same as the input), the remaining elements of the array will match any sets of brackets in the expression. Therefore $matches[1] will be your two digits:
if(preg_match("/^view-(\d\d)$/",$variable,$matches)) {
$result = $matches[1];
}
You should use preg_match. Example:
if(preg_match(<<regular expression>>, $variable))
{
$variable1 = 1;
}
else
{
$variable2 = 2;
}
Also consider the ternary operator if you are only doing an assignment:
$variable2 = preg_match(<<regular expression>>, $variable) ? 1 : 2;
Related
I'm trying to store expression in variable and then use it in array_filter to return data based on this value for example
$condition = '== 100';
$test = array_filter($last,function ($data)use ($condition){
return $data['rating'] .$condition;
});
var_dump($test);
I tried to use html_entity_decode($condition, ENT_QUOTES); preg_replace( ) str_replace() as well as trim in order to remove the single quotes but it didn't work
I have many condition and I don't want to write array_filter many times is there a way to do this ? or better way then the one I'm trying to achieve.
I assumed that you have a limited number of comparison operators you are considering. For reasons of simplicity I numbered them 0,1,2,.... They will trigger different kinds of comparisons inside your filter callback function:
funcion myfiltarr($arr,$operator,$value){
$test = array_filter($last,function ($data) use ($operator, $value){
$v=$data['rating'];
switch($operator) {
case 0: return $v == $value;
case 1: return $v < $value;
case 2: return $v > $value;
case 9: return preg_match($value,$v);
// to be extended ...
default: return true;
}
});
return $test
}
$test=myfiltarr($last,0,100); // test: "== 100"
var_dump($test);
$test=myfiltarr($last,9,'/^abc/'); // test: "match against /^abc/"
var_dump($test);
Edit: I extended the original answer by a preg_match() option (comparison code: 9). This option interprets the given $value as a regular expression.
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 am trying to understand the basic PHP code in this video, which demonstrates how you can list all the positions of a specific string within a larger string (in this case, all the positions of $find within $string will be listed):
<?php
$find = 'is';
$find_leng = strlen($find);
$string = 'This is a string, and it is an example.';
while ($string_position = strpos($string, $find, $offset)) {
echo '<strong>'.$find.'</strong> found at '.$string_position.'<br>';
$offset = $string_position + $find_length;
}
?>
What confuses me is that within the () of the while-loop, it seems that a new variable $string_position is being declared. But doesn't the while-loop take an input of 0 or 1, a Boolean? The $string_position variable is not a true/false variable, it is meant to store the position of the string it is passed with the strpos() function.
The basic while-loop I'm used to uses a comparison operator like this one from from w3schools:
<?php
$x = 1;
while($x <= 5) {
echo "The number is: $x <br>";
$x++;
}
?>
Can a variable be declared in a while-loop? And if that is the case, how does it work in this example? This is my first question on Stack Overflow so hopefully I'm posting this in the right place and it's not too newbie of a question.
Yes, while loops take boolean-like as arguments. By doing
while ($string_position = strpos($string, $find, $offset)) {
it first executes what is inside the parenthesis, then evaluates the result of that to determine if the loop should quit or not.
strpos will return False if the needle was not found, so $string_position will be false and as such the evaluation result will also be False and the loop will quit. If the needle is found, then loop continues after the attribution.
Also it should be noted that strpos might return a non-boolean that evaluates to False, so be careful with that construction.
Reference on strpos
In most programming languages, if a variable exists and isn't 0 or False, then it counts as a 1 or True.
In this example:
if ($str="hey"){
echo $str;
};
It will output hey because the variable was successfully declared and isn't 0.
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.
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);
}