Preg_match if a string beginns with "00"{number} or "+"{number} - php

I have to test if a string begins with 00 or with +.
pseudocode:
Say I have the string **0090** or **+41**
if the string begins with **0090** return true,
elseif string begins with **+90** replace the **+** with **00**
else return false
The last two digits can be from 0-9.
How do I do that in php?

You can try:
function check(&$input) { // takes the input by reference.
if(preg_match('#^00\d{2}#',$input)) { // input begins with "00"
return true;
} elseif(preg_match('#^\+\d{2}#',$input)) { // input begins with "+"
$input = preg_replace('#^\+#','00',$input); // replace + with 00.
return true;
}else {
return false;
}
}

if (substr($str, 0, 2) === '00')
{
return true;
}
elseif ($str[0] === '+')
{
$str = '00'.substr($str, 1);
return true;
}
else
{
return false;
}
The middle condition won't do anything though, unless $str is a reference.

if (substr($theString, 0, 4) === '0090') {
return true;
} else if (substr($theString, 0, 3) === '+90') {
$theString = '00' . substr($theString, 1);
return true;
} else
return false;

Related

preg_match - For sure there is a better way to search for these characters

So, I want to check the users-input, if it contains some of these characters:
" ' < >
I hope someone can show me a better way with less code
Thanks!
I used preg_match, but i just managed it with 4 nested if's.
/*Checks if the given value is valid*/
private function checkValidInput($input)
{
/*If there is no " */
if(preg_match('/"/', $input) == false)
{
/*If there is no ' */
if(preg_match("/'/", $input) == false)
{
/*If there is no <*/
if(preg_match("/</", $input) == false)
{
/*If there is no >*/
if(preg_match("/>/", $input) == false)
{
return true;
}
else
{
return false;
}
}
else
{
return false;
}
}
else
{
return false;
}
}
else
{
return false;
}
}
You could create a regex class
preg_match('#["\'<>]#', $input);
Edit:
If you need to check for all characters then use strpos() with for loop
function checkInput($val) {
$contains = true;
$required = "<>a";
for($i = 0, $count = strlen($required); $i < $count ; ++$i) {
$contains = $contains && false !== strpos($val, $required[$i]);
}
return $contains;
}
var_dump(checkInput('abcd<>a')); // true
var_dump(checkInput('abcd>a')); // false, doesn't contain <

Is string a math expression?

How can I found if string is a math expression or not?
It is enough to understand basic math expressions +, -, x, /
For Example:
"1+1" => TRUE
"2 / 2" => TRUE
"hello" => FALSE
"1 * 2 - X" => FALSE
"me + u" => FALSE
class MathExpression {
private static $parentheses_open = array('(', '{', '[');
private static $parentheses_close = array(')', '}', ']');
protected static function getParenthesesType( $c ) {
if(in_array($c,MathExpression::$parentheses_open)) {
return array_search($c, MathExpression::$parentheses_open);
} elseif(in_array($c,MathExpression::$parentheses_close)) {
return array_search($c, MathExpression::$parentheses_close);
} else {
return false;
}
}
public static function validate( $expression ) {
$size = strlen( $expression );
$tmp = array();
for ($i=0; $i<$size; $i++) {
if(in_array($expression[$i],MathExpression::$parentheses_open)) {
$tmp[] = $expression[$i];
} elseif(in_array($expression[$i],MathExpression::$parentheses_close)) {
if (count($tmp) == 0 ) {
return false;
}
if(MathExpression::getParenthesesType(array_pop($tmp))
!= MathExpression::getParenthesesType($expression[$i])) {
return false;
}
}
}
if (count($tmp) == 0 ) {
return true;
} else {
return false;
}
}
}
//Mathematical expressions to validate
$tests = array(
'(A1+A2*A3)+A5+(B3^B5)*(C1*((A3/C2)+(B2+C1)))',
'(A1+A2*A3)+A5)*C1+(B3^B5*(C1*((A3/C2)+(B2+C1)))',
'(A1+A2*A3)+A5++(B2+C1)))',
'(A1+A2*A3)+A5+(B3^B5)*(C1*(A3/C2)+(B2+C1))'
);
// running the tests...
foreach($tests as $test) {
$isValid = MathExpression::validate( $test );
echo 'test of: '. $test .'<br>';
var_dump($isValid);
}
you can check and read in detail about the solution here Is there possible to check mathematical expression string?
See also eval. For example, you can do this:
$result = INF;
try {
eval("$result=" + myMathExpression); // Evaluate here
} catch (Exception $e) {
}
if($result != INF) echo("Expression is a valid mathematical expression.");
read more about it there
An extremely simple solution:
Regex number,whitespace,[+,/,*,-,=],whitespace,Substring(recursion here)
will work for any sequence of
1 + 1 + 2 + ... + 1 = 2 + 3 + 4 = 1 * 4 ...
etc.
Obviously would not check if an expression is legit.
As per request, pseudo code:
if Regex(^(([0-9]+)(\s*)([+,/,*,-,=])(\s*)([0-9]+)(\s*)([+,/,*,-,=])(\s*)))
if (recursion())
return True;
else
return False;
else //checking for end point
if Regex(^(([0-9]+)(\s*)([+,/,*,-,=])(\s*)([0-9]+)))
return True;
else
return False;
Maybe a regex with a pattern like this :
^([-+/*]\d+(\.\d+)?)*

Function returning boolean only returns false

I've a simple function that apprently puts me up with a lot of trouble. The function is:
function valid_mail($email) {
$atpointers = strstr($email, "#");
$spacepointers = count(explode(" ", $email));
$dotpointers = strstr($email, ".");
$ltpointers = strstr($email, "<");
$gtpointers = strstr($email, ">");
$illegalpts = $ltpointers + $gtpointers;
if($atpointers >= 2 || $dotpointers == 0 || strlen($email) <= 6 || $illegalpts >= 1) { return false; } else { return true; }
}
And calling it in the context:
if(valid_mail($email) === false) { // Code } else { // Code }
The problem is apparently it only returns false. Any ideas for why this happens ?
strstr returns a substr of the string being checked, not a length. Use strpos instead.

PHP remove all characters before specific string

I need to remove all characters from any string before the occurrence of this inside the string:
"www/audio"
Not sure how I can do this.
You can use strstr to do this.
echo strstr($str, 'www/audio');
Considering
$string="We have www/audio path where the audio files are stored"; //Considering the string like this
Either you can use
strstr($string, 'www/audio');
Or
$expStr=explode("www/audio",$string);
$resultString="www/audio".$expStr[1];
I use this functions
function strright($str, $separator) {
if (intval($separator)) {
return substr($str, -$separator);
} elseif ($separator === 0) {
return $str;
} else {
$strpos = strpos($str, $separator);
if ($strpos === false) {
return $str;
} else {
return substr($str, -$strpos + 1);
}
}
}
function strleft($str, $separator) {
if (intval($separator)) {
return substr($str, 0, $separator);
} elseif ($separator === 0) {
return $str;
} else {
$strpos = strpos($str, $separator);
if ($strpos === false) {
return $str;
} else {
return substr($str, 0, $strpos);
}
}
}
You can use substring and strpos to accomplish this goal.
You could also use a regular expression to pattern match only what you want. Your mileage may vary on which of these approaches makes more sense.

substr strpos help

The script below pulls a summary of the content in $description and if a period is found in the first 50 characters, it returns the first 50 characters and the period. However, the flaw is, when no period exists in the content, it just returns the first character.
function get_cat_desc($description){
$the_description = strip_tags($description);
if(strlen($the_description) > 50 )
return SUBSTR( $the_description,0,STRPOS( $the_description,".",50)+1);
else return $the_description;}
I'd like to make it so that if no period is found, it returns up until the first empty space after 50 characters (so it doesn't cut a word off) and appends "..."
Your best bet is to use regular expression. This will match your $description up to $maxLength (2nd argument in function) but will continue until it finds the next space.
function get_cat_desc($description, $max_length = 50) {
$the_description = strip_tags($description);
if(strlen($the_description) > $max_length && preg_match('#^\s*(.{'. $max_length .',}?)[,.\s]+.*$#s', $the_description, $matches)) {
return $matches[1] .'...';
} else {
return $the_description;
}
}
I think it just needs to be a little more complicated:
function get_cat_desc($description){
$the_description = strip_tags($description);
if(strlen($the_description) > 50 ) {
if (STRPOS( $the_description,".",50) !== false) {
return SUBSTR( $the_description,0,STRPOS( $the_description,".",50)+1);
} else {
return SUBSTR( $the_description,0,50) . '...';
}
} else {
return $the_description;
}
}
Try something like this:
$pos_period = strpos($the_description, '.');
if ($pos_period !== false && $pos_period <= 50) {
return substr($the_description, 0, 50);
} else {
$next_space = strpos($the_description, ' ', 50);
if ($next_space !== false) {
return substr($the_description, 0, $next_space) . '...';
} else {
return substr($the_description, 0, 50) . '...';
}
}
use substr_count to find it and then do substr(,0,50)

Categories