PHP search in a variable text and save it - php

I have this autogenerated variable:
$var = "WXYZ 300700Z 32011KT 9999 FEW035 SCT200 24/16 Q1007 NOSIG";
How can I search and save "9999" in this var? I cant use substr cause $var's value is always changing and it is always in another "place" in the variable. It is always 4 numbers.

You can match 4 numbers wrapped by word boundaries or space characters, depending on what you need with regular expression (regex/regexp).
if( preg_match('/\b([0-9]{4})\b/', $var, $matches) > 0 ) {
// $matches[1] contains the number
}
Note, however, that the word boundary match will also match on non-letter characters (symbols like dollar sign ($), hyphen (-), period (.), comma (,), etc.). So a string of "XYZ ABC 9843-AB YZV" would match the "9843". If you want to just match based on numbers surrounded by white space (spaces, tabs, etc) you can use:
if( preg_match('/(?:^|\s)([0-9]{4})(?:\s|$)/', $var, $matches) > 0 ) {
// $matches[1] contains the number
}

Using explode is the way to go, we need to turn the string into an array, our variables are separated by white space, so we get a variable every time we face a white space " ", i made another example to understand how explode works.
<?php
$var = "WXYZ 300700Z 32011KT 9999 FEW035 SCT200 24/16 Q1007 NOSIG";
print_r (explode(" ",$var)); //Display the full array.
$var_search = explode(" ",$var);
echo $var_search[3];//To echo the 9999 (4th position).
?>
<br>
<?php
$var = "WXYZ+300700Z+32011KT+9999+FEW035+SCT200+24/16+Q1007+NOSIG";
print_r (explode("+",$var)); //Display the full array.
$var_search = explode("+",$var);
echo $var_search[3];//To echo the 9999 (4th position).
?>
I hop this is what you're looking for

Is this viable?
$var = "WXYZ 300700Z 32011KT 9999 FEW035 SCT200 24/16 Q1007 NOSIG";
if (strpos($var, '9999') == true {
// blah blah
}
else{
echo 'Value not found'
}
Personally haven't tested this yet, but I think you're looking for something along these lines...

Hello I would use a preg_match regex using this regular expression : \d{4}

here is the solution
var str1 = "WXYZ 300700Z 32011KT 9999 FEW035 SCT200 24/16 Q1007 NOSIG";
var str2 = "9999";
if(str1.indexOf(str2) != -1){
console.log(str2 + " found");
}

Related

PHP - Check for leading 0's in 2 comma-delimited integers

I have a user-input string with 2 comma-delimited integers.
Example (OK):
3,5
I want to reject any user input that contains leading 0's for either number.
Examples (Bad):
03,5
00005,3
05,003
Now what I could do is separate the two numbers into 2 separate string's and use ltrim on each one, then see if they have changed from before ltrim was executed:
$string = "03,5";
$string_arr = explode(",",$string);
$string_orig1 = $string_arr[0];
$string_orig2 = $string_arr[1];
$string_mod1 = ltrim($string_orig1, '0');
$string_mod2 = ltrim($string_orig2, '0');
if (($string_mod1 !== $string_orig1) || ($string_mod2 !== $string_orig2)){
// One of them had leading zeros!
}
..but this seems unnecessarily verbose. Is there a cleaner way to do this? Perhaps with preg_match?
You could shorten the code and check if the first character of each part is a zero:
$string = "03,5";
$string_arr = explode(",",$string);
if ($string_arr[0][0] === "0" || $string_arr[1][0] === "0") {
echo "not valid";
} else {
echo "valid";
}
Here is one approach using preg_match. We can try matching for the pattern:
\b0\d+
The \b would match either the start of the string, or a preceding comma separator.
If we find such a match, it means that we found one or more numbers in the CSV list (or a single number, if only one number present) which had a leading zero.
$input = "00005,3";
if (preg_match("/\b0\d+/", $input)) {
echo "no match";
}
You can do a simple check that if the first character is 0 (using [0]) or that ,0 exists in the string
if ( $string[0] == "0" || strpos($string, ",0") !== false ) {
// One of them had leading zeros!
}
All the current answers fail if any of the values are simply 0.
You can just convert to integer and back and compare the result.
$arr = explode(',', $input);
foreach($arr as $item) {
if( (str)intval($item) !== $item ) {
oh_noes();
}
}
However I am more curious as to why this check matters at all.
One way would be with /^([1-9]+),(\d+)/; a regex that checks the string starts with one or more non-zero digits, followed by a comma, then one or more digits.
preg_match('/^([1-9]+),(\d+)/', $input_line, $output_array);
This separates the digits into two groups and explicitly avoids leading zeros.
This can be seen on Regex101 here and PHPLiveRegex here.

How to check a string for a given format using PHP?

I have many headlines in my project like:
00.00.2014 - Headline Description e.t.c.
I want to check with php if the given strings contain the format 00.00.0000 - in front. The part after the - doesn't matter.
Can someone help me with something like:
$format = '00.00.0000 -';
if ($string MATCHES $format IN FRONT) {
// ...some code...
}
This should work:
if (preg_match("/^\d{2}\.\d{2}\.\d{4}\s\-\s.*$/", $string) === 1) {
// $string matches!
}
Explanation:
^ is "the beginning of the string"
\d is any digit (0, 1, 2, ..., 9)
{n} means "repeated n times"
\. is a dot
\s is a space
\- is a minus sign
. is "any single character"
* means "repeated 0 or more times`
$ means "end of the string"
I don't have a dev environment to test this out on but i'll give you some psuedocode:
I'm unsure of the context, but you can test this function on any given STRING:
Function:
Boolean hasCorrectFormat($myString){
//Here take the string and cut it into a char array.
$charArray = str_split($myString);
//This will give you a char array. Compare the first 12 elements of this
//array to see if they are correct. If its supposed to be number make
//sure it is, if its supposed to be a "." make sure it is..etc
//"00.00.0000 -" is 12 characters.
if(!isNumeric(charArray[0])){
return false;
}
else if(!isNumeric(charArray[1])){
return false;
}
else if(charArray[2] != "."){
return false;
}
//so on and so forth.....
else {return true}
}
Like i said i can't test this, and i can almost guarantee you this code wont run. This should give you the logic involved though.
Edit: also i wrote this assuming you dont literally mean "00.00.0000" but rather "xx.xx.xxxx" x being any number 0-9. If you need to make sure it is literally zeros then just cut your string to be the first ten chars and compare it.
Use the strpos function. Something like this:
if (strpos($string,'00.00.0000 -') !== true) {
//some code
}

preg_match numbers and comma

I have some values like 4,3 or 5 for instance.
I want to allow only the numbers (from 0 to 9) and the comma.
I found this function, pregmatch but it's not working correctly.
<?php
$regex="/[0-9,]/";
if(!preg_match($regex, $item['qty'])){
// my work
}
?>
What's wrong ?
Thanks
Corrected syntax:
$regex="/^[0-9,]+$/";
^ represents start of line
+ represents one or more of the group characters
$ represents end of line
This should do it:
'~^\d+(,\d+)?$~'
It allows e.g. 1 or 11,5 but fails on 1, or ,,1 or ,,
^ Start of
\d+ followed by one or more digits
(,\d+)? optional: comma , followed by one or more digits
$ end
\d is a shorthand for digit [0-9]
You asked what's wrong with $regex="/[0-9,]/";
It would match any 0-9 or , which are in the [characterclass]. Even, when matching a string like abc1s or a,b because no anchors are used.
If you know it will be a comma-separated list then use explode():
<?php
// test item with incorrect entries
$item = '1,2,3,4,d,#,;';
// explode whatever is between commas into an array
$item_array = explode(',', $item);
// loop through the array (you could also use array_walk())
foreach($item_array as $key => $val)
{
// to clean it
$item_array[$key] = (int) $val;
// use the values here
}
// or here
?>
<?php
$regex = '/^[0-9,]+$/';
if(!preg_match($regex, $item['qty'])) {
// my work
}
?>

What's going on with this preg_match?

$var = 3;
if ($cleanvar = preg_match('/^[0-9]{0,2}$/', $var))
{
echo $cleanvar; echo $var; exit();
}
else
. . .
Strange output. This is causing my cleanvar to echo 1 and var still echo's 3. Why is this happening? The point of this regex is to only match whole numbers, as 1 or 2 digits. e.g.( 1, 2, 4, 38, 24)
Is their an issue in my Regex? Or what is causing this odd behavior?
$cleanvar is just true or false. You're looking for a number between 0 and 2 digits in length (from the beginning to the end of the string, so no other characters are allowed).
EDIT: it returns 1 if matched, 0 if not.
See this for more information: http://us3.php.net/preg_match
$var should be followed by an array if you want it set. You might wish to change to {1,2} if matching >=1.
Your regex is correct, and it is matching correct. Just that preg_match returns 1 if you get a match and 0 if it doesn't. See the documentation.
If you are trying to validate an input value, you only need look at the return of preg_match. Using the + operator matches "one or more of the preceding element."
if (preg_match('/^[0-9]+$/', $var)) {
// we matched a number only, so we know $var is clean
} else {
}
If you need to extract a number from an input field, you can use capture groups:
if (preg_match('/([0-9]+)/', $var, $matches)) {
$num = $matches[1];
} else {
}
Note that this does not match the entire input, but will return on the first number it finds in the input $var.

Replace Leading zero with '+' in PHP

I want to replace the leading zero in a phone number with '+' and country code.
If the phone number starts with zero (ex: 07512345678) then I want to remove the leading zero and replace with '+' and country code else (ex: 7512345678)just add '+' and country code.
What would the way to do that in PHP?
Use preg_replace()
$newNumber = preg_replace('/^0?/', '+'.$countryCode, $phoneNumber);
The first parameter is the regular expression, which is looking for that leading zero of yours. The second is what you want to replace it with (the plus sign concatenated with the country code.). Finally, $phoneNumber is the original phone number.
The replaced value is assigned to the variable $newNumber. Feel free to change the variables to fit your code.
Use substr_replace(), no need for regex or if blocks.
$number = '07512345678';
$country_code = '44';
$new_number = substr_replace($number, '+'.$country_code, 0, ($number[0] == '0'));
You could use preg_replace:
$newNumber = preg_replace("/^0/", "+", 07512345678)
This will replace the first character of each number if and only if it is zero. The regular expression used is: /^0/. The ^ tells it to look at the first character, and then only match a 0 thereafter. This 0 will be replaced with the second argument, the "+". The last argument is the source string.
Reference
Take a look at preg_replace here
Basic syntax for beginning REGEX here
You can use string manipulation:
$x = '012345678';
if ($x[0]=='0') $x[0] = ''; // delete leading zero
$x = '+1'.$x;
preg_match() is less effective I suspect, due to the complexity of the whole system.
<?php
$countryCode = "XX";
$phone = array("0123455", "7837373");
foreach( $phone AS $number ) {
if( $number[0] == '0' ) {
$number = "+{$countryCode}" . substr($number,1);
}
echo "{$number}\n";
}
PS: this is elementary. You should really got through some tutorials.

Categories