This question already has answers here:
How to check if a string contains certain characters using an array in php
(5 answers)
Closed 12 months ago.
I want to validate that a string consists of numbers or commas or semicolons:
valid: 1.234
valid: 1,234
invalid: 1.23a
invalid: 1.2_4
What works:
use str_split to create an array out of the string and use in_array with array(0,1,2,3,4,5,6,7,8,9,',',';').
But this feels circuitous to me and since I have to do this with millions of strings I want to make sure there is no more efficient way.
Question: Is there a more efficient way?
If you only need to validate a string (not sanitize or modify it), you can use regex. Try the following:
if (preg_match('/^[0-9\,\;\.]+$/', $string)) {
// ok
} else {
// not ok
}
The solution using preg_match function:
// using regexp for (numbers OR commas OR semicolons) - as you've required
function isValid($str) {
return (bool) preg_match("/^([0-9.]|,|;)+$/", $str);
}
var_dump(isValid("1.234")); // bool(true)
var_dump(isValid("1.23a")); // bool(false)
var_dump(isValid("1,234")); // bool(true)
Related
This question already has answers here:
How to loop through PHP object with dynamic keys [duplicate]
(16 answers)
Closed 4 years ago.
I get the content from an URL: http://money18.on.cc/js/real/hk/quote/16981_r.js
The content of this file is something like this:
M18.r_16981 = {
"ltt": '2018/06/21 11:43',
"np": '0.050',
"iep": '0.000',
"iev": '0',
"ltp": '0.050',
"vol": '940000',
"tvr": '49860',
"dyh": '0.060',
"dyl": '0.049'
};
I want to extract the number after "vol", i.e. 940000.
And this is my php:
<?php
$content = file_get_contents("http://money18.on.cc/js/real/hk/quote/16981_r.js");
echo $content."<br>";
preg_match("/(?<=vol\": ').*(?=', \"tvr)/", $content, $output_array);
print_r(array_values($output_array));
?>
The result returns nothing. Is the Regex wrong or any other problem?
Thanks.
In your positive lookahead (?= you could replace the whitespace with \s* to match zero or more (or \s+ to match one or more) whitespace characters.
(?<=vol": ').*(?=',\s*"tvr)
Regex demo
Php demo
Bit of a long shot but...
If that content is actually meant to represent JSON and you have control over it:
get it into proper format as it is much easier and secure to get the data you want out of it then.
$jsonString = <<<JSON
{
"ltt": "2018/06/21 11:43",
"np": "0.050",
"iep": "0.000",
"iev": "0",
"ltp": "0.050",
"vol": "940000",
"tvr": "49860",
"dyh": "0.060",
"dyl": "0.049"
}
JSON;
$jsonAsArray = json_decode($jsonString, true);
var_dump($jsonAsArray['vol']);
This question already has answers here:
Insert string at specified position
(11 answers)
separate string in two by given position
(8 answers)
Closed 4 years ago.
I want to explode a string or an integer and separate it by a space.
E.g., I have this int 12345678, and I want its numbers to become like 123 45678. I want the first three numbers separated. Can someone give me a clue or hint in how to achieve this, like what function to use in PHP? I think using an explode will not work here because the explode function needs a separator.
You can use substr_replace() - Replace text within a portion of a string.
echo substr_replace(1234567, " ", 3, 0); // 123 4567
https://3v4l.org/9CFlX
You could use substr() :
$str = "12345678" ;
echo substr($str,0,3)." ".substr($str, 3); // "123 45678"
Also works with an integer :
$int = 12345678 ;
echo substr($int,0,3)." ".substr($int, 3); // "123 45678"
This problem will solve by using substr().
The substr() function returns a part of a string.
Syntax: substr(string,start,length)
Example:
$value = "12345678";
echo substr($value,0,3)." ".substr($value, 3);
Output: 123 45678
You may get better understand from here.
This question already has answers here:
How do I check if a string contains a specific word?
(36 answers)
Closed 9 years ago.
Intro
In search, i want to make search for age range.
if a user inserts a '-' included input like 10-30 this way
i will display list of people age greater than 10 and less than 30.
My Question
$q = mysql_real_escape_string(htmlspecialchars("user input from search field"));
From here before entering to make query i want to make two conditions,
One: if there's a '-' in user input or not ? if yes i want to query as according, if not the other way.
So, how can i enter into the first condition ?
This will work:
// use strpos() because strstr() uses more resources
if(strpos("user input from search field", "-") === false)
{
// not found provides a boolean false so you NEED the ===
}
else
{
// found can mean "found at position 0", "found at position 19", etc...
}
strpos()
What NOT to do
if(!strpos("user input from search field", "-"))
The example above will screw you over because strpos() can return a 0 (zero) which is a valid string position just as it is a valid array position.
This is why it is absolutely mandatory to check for === false
Simply use this strstr function :
$string= 'some string with - values ';
if(strstr($string, '-')){
echo 'symbol is isset';
}
This question already has answers here:
Search in array with relevance
(5 answers)
Closed 9 years ago.
I am trying to search an array for a list of words(areas).
But sometime the word(area) in the array is 2 words.
i.e in the array is "Milton Keynes" so "Milton" is not being matched
Is there any way i can do this, without splitting any double words in the array (as i assume this will be a big load on the server)
Below is an example of what i am doing
foreach (preg_split("/(\s)|(\/)|(\W)/", $words) as $word){
if (in_array($word, $areaArray)){
$AreaID[] = array_search($word, $areaArray);
}
}
Grateful, as always for any advice!
You could use preg_grep():
$re = sprintf('/\b%s\b/', preg_quote($search, '/'));
// ...
if (preg_grep($re, $areaArray)) {
// we have a match
}
You can opt to make the match case insensitive by adding the /i modifier.
You can use regular expression to find a value, this will work similar to MySQL like function
$search='Milton Keynes';
foreach ($areaArray as $key => $value) {
if (preg_match('~'.preg_quote($search).'~i',$value)) {
echo "$key";
}
}
This question already has answers here:
php validate integer
(7 answers)
Closed 9 years ago.
Hey I'm trying to perform input validation in PHP to ensure that the stock values that are typed in are at least 1 positive integer and from 0-9. Should not contain any special characters.
For example, any of the following values should be valid:
7
0
32
47534
The following SHOULD NOT be valid:
asdf
35/gdf
../34.
etc..
I'm using the following if statement to check for the positive integer value of "$original_stock".
if (preg_match("/^[0-9]$/", $original_stock))
{
$error .="Original stock must be numerical.";
}
Additionally, I have a price field which should be validated as either an int or a double.
If there's an easier alternative to using regex, that's okay too!
Thanks in advance :)
Try this regexp:
/^\d+$/
The issue with your existing regexp is that it only matches strings with exactly one digit.
As for validating an int or a double:
/^\d+\.?\d*$/
Note that that regexp requires that there be at least one digit.
Use:
/^[0-9]+$/
The + means "one or more". Without it, your regex will only match a single digit. Or you could use the simpler variant:
/^\d+$/
For floats, try something like:
/^\d+(\.\d{1,2})?/
This will match one or more digits, optionally followed by a . and one or two digits. (i.e. .12 will not match.)
To save yourself some headaches, you can also use the is_int and is_float functions.
Lastly; note that your check is wrong. preg_match will return 0 if it fails, so you should write it as:
if (!preg_match("/^\+$/", $original_stock)) {
// error
}
(note the !).
You may want to use the
is_int
Don't reinvent a wheel slower than an existing one, use a motorcycle: is_int.
#Assuming $original_stock is a single value...
if (is_int($original_stock)) {
#Valid, do stuff
}
else {
#Invalid, do stuff
}
#Assuming $original_stock is an array...
$valid = true;
foreach ($original_stock as $s) {
if (!is_int($s)) {
$valid = false;
break;
}
}
if ($valid) {...}
else {...}
I just ran into this exact problem and solved it this way using the regex.
I think the problem is your caret ^.
/^[0-9]$/
I moved it inside the class and got the results I needed.
function validate_int($subject)
{
//Pattern is numbers
//if it matches anything but numbers, we want a fail
$pattern = '/[^0-9]/';
$matches = preg_match($pattern, $subject);
if($matches > 0)
return false;
else
return true;
}