I have a database with 5000 entries of local area codes to separate the area code from a phone number string. Area Codes could be a part of other Area Codes. For example
0212 Solingen
02129 Haan
The Area Code of Solingen is a Part of the Area Code of Haan.
Question: Should i store all entries in an array or should i search directly in SQL till the final result?
Question: How can i get the entrie with the most found digits while area codes can be double in array / SQL
The Code i use is
The Result is "03491 52023" which is wrong; It should be "034915 2023"
<?php
$area_codes = array( '0350', '034', '034915', '03491', '0348', '0349', '03491', '034916', '034917',);
$phone = '0349152023';
foreach ($area_codes as $code) {
if (substr($phone, 0, strlen($code)) == $code) {
$phone_string = substr($phone, 0, strlen($code))." ".substr($phone, strlen($code));
}
}
if (!empty($phone_string)) {
echo $phone_string;
}
else {
echo "No AreaCode found.";
}
?>
Thanks for your help.
You just need to sort array and you will get desired output:
Working Demo: https://eval.in/871329
$area_codes = array( '0350', '034', '034915', '03491', '0348', '0349', '03491', '034916', '034917',);
sort($area_codes);
$phone = '0349152023';
foreach ($area_codes as $code) {
$subString = substr($phone, 0, strlen($code)); // stored in var so no need to re-code for substr
if ($subString == $code) {
$phone_string = $subString." ".substr($phone, strlen($code));
}
}
if (!empty($phone_string)) {
echo $phone_string;
}
else {
echo "No AreaCode found.";
}
Output:
034915 2023
Related
I need help with my PHP website. I need to search if textbox includes some text. Its working only on half. When I type "Kdy" it works but when I type "Kdy prijdes" it wont work. I need to change output when textbox includes some part of textbox but my idea wont work. Any solutions?
<h1>Zeptej se mě</h1>
<form id="frm" method="POST" action="?action">
<input type = "text" name = "textbox" value = ""/>
<input type="submit" value="Odešli" id="submit"/>
</form>
<?php
if(isset($_GET['action']))
{
$text = $_POST['textbox'];
$kde = array("kde", "Kde");
$kam = array("kam", "Kam");
$kdy = array("kdy", "Kdy");
$jak = array("jak", "Jak");
$co = array("co", "Co");
$proc = array("proč", "proc", "Proč", "Proc");
$kdo = array("kdo", "Kdo");
$koho = array("koho", "Koho");
if (in_array($text, $kde))
{
echo "Nikde";
}
elseif(in_array($text, $kam))
{
echo "Nikam";
}
elseif(in_array($text, $kdy))
{
echo "Nikdy";
}
elseif(in_array($text, $jak))
{
echo "Nevim";
}
elseif(in_array($text, $co))
{
echo "Nic";
}
elseif(in_array($text, $proc))
{
echo "Nevim";
}
elseif(in_array($text, $kdo))
{
echo "Nikdo";
}
elseif(in_array($text, $koho))
{
echo "Nikoho";
}
else
{
$text = array("Spíš ne", "Asi", "No nevím");
echo $text[array_rand($text)];
}
}
?>
I would try to find a solution for this using strpos()
so if you check for a specific part of text it could look like this:
if(strpos($text, "Kdy") !== false){
//do something
}
Another approach could be to explode() the $text into its parts and compare the array with an array of strings you want to check for.
But there might be smarter solutions for this.
You can use next simple function:
<?php
function find_text($text) {
// convert input text to lower case
$text = strtolower($text);
// build dictionary with responses on each word
$dict = [
"kde" => "Nikde",
"kam" => "Nikam",
"kdy" => "Nikdy",
"jak" => "Nevim",
"co" => "Nic",
"proč" => "Nevim",
"proc" => "Nevim",
"kdo" => "Nikdo",
"koho" => "Nikoho",
];
// loop trough dictionary
foreach($dict as $find=>$response) {
if (false !== strpos($text, $find)) {
// immediately return response when one of dictionary words found
return $response;
}
}
// if input cot contains no one of dictionary words return 'not found'
$text = array("Spíš ne", "Asi", "No nevím");
return $text[array_rand($text)];
};
// echo find_text('"Kdy prijdes"');
if(isset($_GET['action']))
{
echo find_text($_POST['textbox']);
}
?>
You can test PHP code here
I am trying to GET different rows from different columns in php/mysql, and pack them into an array. I am able to successfully GET a jason encoded array back IF all values in the GET string match. However, if there is no match, the code echos 'no match', and without the array. I know this is because of the way my code is formatted. What I would like help figuring out, is how to format my code so that it just displays "null" in the array for the match it couldn't find.
Here is my code:
include '../db/dbcon.php';
$res = $mysqli->query($q1) or trigger_error($mysqli->error."[$q1]");
if ($res) {
if($res->num_rows === 0)
{
echo json_encode($fbaddra);
}
else
{
while($row = $res->fetch_array(MYSQLI_BOTH)) {
if($_GET['a'] == "fbaddra") {
if ($row['facebook'] === $_GET['facebook']) {
$fbaddr = $row['addr'];
} else {
$fbaddr = null;
}
if ($row['facebookp'] === $_GET['facebookp']) {
$fbpaddr = $row['addr'];
} else {
$fbpaddr = null;
}
$fbaddra = (array('facebook' => $fbaddr, 'facebookp' => $fbpaddr));
echo json_encode($fbaddra);
}
}
}
$mysqli->close();
UPDATE: The GET Request
I would like the GET request below to return the full array, with whatever value that didn't match as 'null' inside the array.
domain.com/api/core/engine.php?a=fbaddra&facebook=username&facebookp=pagename
The GET above currently returns null.
Requests that work:
domain.com/api/core/engine.php?a=fbaddra&facebook=username or domain.com/api/core/engine.php?a=fbaddra&facebookp=pagename
These requests return the full array with the values that match, or null for the values that don't.
TL;DR
I need assistance figuring out how to format code to give back the full array with a value of 'null' for no match found in a row.
rather than assigning as 'null' assign null. Your full code as follows :
include '../db/dbcon.php';
$res = $mysqli->query($q1) or trigger_error($mysqli->error."[$q1]");
if ($res) {
if($res->num_rows === 0)
{
echo json_encode('no match');
}
else
{
while($row = $res->fetch_array(MYSQLI_BOTH)) {
if($_GET['a'] == "fbaddra") {
if ($row['facebook'] === $_GET['facebook']) {
$fbaddr = $row['dogeaddr'];
//echo json_encode($row['dogeaddr']);
} else {
$fpaddr = null;
}
if ($row['facebookp'] === $_GET['facebookp']) {
$fbpaddr = $row['dogeaddr'];
//echo json_encode($row['dogeaddr']);
} else {
$fbpaddr = null;
}
$fbaddra = (array('facebook' => $fbaddr, 'facebookp' => $fbpaddr));
echo json_encode($fbaddra);
}
}
}
$mysqli->close();
You can even leave else part altogether.
Check your code in this fragment you not use same names for variables:
if ($row['facebook'] === $_GET['facebook']) {
$fbaddr = $row['dogeaddr'];
//echo json_encode($row['dogeaddr']);
} else {
$fpaddr = 'null';
}
$fbaddr not is same as $fpaddr, this assign wrong result to if statement.
It was the mysql query that was the problem.
For those who come across this, and need something similar, you'll need to format your query like this:
** MYSQL QUERY **
if ($_GET['PUTVALUEHERE']) {
$g = $_GET['PUTVALUEHERE'];
$gq = $mysqli->real_escape_string($g);
$q1 = "SELECT * FROM `addrbook` WHERE `facebookp` = '".$gq."' OR `facebook` = '".$gq."'";
}
** PHP CODE **
if($_GET['PUTVALUEHERE']{
echo json_encode($row['addr']);
}
my questions:
$state=array("你"=>1);
if(array_key_exists("你",$state))
{
$result = array_search("你",$state);echo $result;
}else
{
echo "No Exists";
}
i expect the result of "1", however the output is "No Exists", i don't know why the program can't get the value of the key "你".
array_search will search the given array by value. Try the following:
$state = array("你"=>1);
if(array_key_exists("你", $state)) {
echo $state["你"];
} else {
echo "No Exists";
}
// => 1
» demo
Hope below function will help.
<?php
$array = array('arr1'=>array('find_me'=>'yes you did.'));
function get_value_by_key($array,$key)
{
foreach($array as $k=>$each)
{
if($k==$key)
{
return $each;
}
if(is_array($each))
{
if($return = get_value_by_key($each,$key))
{
return $return;
}
}
}
}
echo get_value_by_key($array,'find_me');
?>
the encoding type of the show paper and the store paper is GB2312.
$state=array("你"=>1);
if(array_key_exists("你",$state))
{
$result1 = $state["你"];
echo $result1; // can get the value 111
}else
{
echo "No Exists";
}
the code above can be executed rightly. i can't show my problems accurately. Now i paste out my code , there is some questions.
<?php
$file = file("GB2312-HanZiBianMa.txt"); // file encoding type ANSI
foreach ($file as $line_num => $line)
{
list($no,$hex,$dec) = preg_split('[\t]',htmlspecialchars($line));;
$result[$hex] = $dec;
}
$result_2 = array_flip($result);
if(array_key_exists("你",$result_2)) // **can't find the value** 222
{
$state= $result_2["你"];
echo $state."<br/>";
}else
{
echo "No Exists<br/>";
}
foreach($result_2 as $k=>$each) //can get the value using the preg_match
{
if(preg_match('/你/', $k))
echo $k."\t".$each."<br/>";
}
?>
the format of GB2312-HanZiBianMa.txt is as follows:
1947 c4e3 你
1948 c4e4 匿
1949 c4e5 腻
1950 c4e6 逆
if your want to test the code , you can save the php code and save the GB2312.. file.
the question is:
why can't the following function get the right value ? the data comes from file and one stores together.
if(array_key_exists("你",$result_2)) // **can't find the value** 222
{
$state= $result_2["你"];
echo $state."<br/>";
}else
{
echo "No Exists<br/>";
}
I have a flatfile database file with the following numbers:
1
2
3
4
5
etc.
The numbers correspond to a USER ID where a person would enter any of those numbers above, in order to login.
I do not want to modify my file. My question is, if there's a way to add an accepted "PREFIX".
For example, a user logs in with:
abcd1
abcd2
abcd3
abcd4
abcd5
etc.
But my data file is still, but does not contain the prefix "abcd":
1
2
3
4
5
etc.
It would also have to be a "perfect" match. The tests I have done so far have not been conclusive
I guess using an accepted "array" would be the way to go?
My present login PHP script is this, but only works on an exact match for a number, I would like to add a prefix that I can change later on:
<?php
date_default_timezone_set('America/New_York');
$today = mktime(0, 0, 0, date("m"), date("d"), date("y"));
$currenttime = date('h:i:s:u');
list($hrs,$mins,$secs,$msecs) = split(':',$currenttime);
echo "<center><form action=\"" . $PHP_SELF . "\" method='post'><input onkeypress=\"return isNumberKey(event)\" type='text' name='uNum' /><input type='submit' value='Submit' /></form></center>";
if(!$_POST['uNum']) {
die('<center>Entrer votre numéro d\'inscription pour finaliser votre demande.</center>');
}
$numbers = file_get_contents("datafile.txt");
$uNumber = $_POST['uNum'];
if ( #preg_match( "/([^0-9]{$uNumber}[^0-9])/", $numbers ) ) {
print_r( "<center>The number $uNumber is good. You may proceed.</b><br><br>" );
file_put_contents($_POST['uNum'].".txt",$_POST['uNum'] . "\nUsed on ".date("m/d/Y", $today). (" $hrs:$mins:$secs")."");
include 'validate_process.php';
if (isset($_POST['uNumber']))
{
$uNumber = $_GET['inscripnum1'];
}
} else {
echo "<center>Sorry, this login number does not exist.</center>";
}
?>
Before you do a preg_match, check if the input has the desired prefix and remove it.
$uNumber = $_POST['uNum'];
$prefix = "abcd"; //you can change the prefix anytime
$length = strlen($prefix);
if(substr($uNumber, 0, $length) === $prefix) {
$uNumber = substr($uNumber,$length);
} else {
$uNumber = ""; //empty or some value that is not a valid ID stored in your flatfile.
}
//Now use $uNumber in preg_match()
if ( #preg_match( "/([^0-9]{$uNumber}[^0-9])/", $numbers ) ) {
//do something
}
Maybe:
if ( #preg_match( "/([^0-9]{abcd$uNumber}[^0-9])/", $numbers ) || #preg_match( "/([^0-9]{$uNumber}[^0-9])/", $numbers ) )
Think that'll work? I never use preg_match
This is one of many ways to do it. Create an array of the file contents and loop through that array:
$numbers = file('datafile.txt');
$result = false;
foreach($numbers as $n) {
if ('abcd'.$n === $uNumber) {
$result = true;
break;
}
}
if ($result) {
// OK!
}
Here's another, where I load the file as an array, add the prefix to each element and then check if the provided value is in that array:
$numbers = file('datafile.txt');
$result = in_array($uNumber,
array_map(function($e) { return 'abcd'.$e; },
$numbers)
);
I am trying to read a file with ip/mask ranges and if the supplied IP matches any range in the file it will return with TRUE or similar function. Here is the code I have below
function myip2long($ip) {
if (is_numeric($ip)) {
return sprintf("%u", floatval($ip));
} else {
return sprintf("%u", floatval(ip2long($ip)));
}
}
function ipfilter($ip) {
$match = 0;
$ip_addr = decbin(myip2long($ip));
if (file_get_contents('./countryip/all-zones/us.zone')) {
$source = file('./countryip/all-zones/us.zone');
foreach ($source as $line) {
$network = explode("/", $line);
$net_addr = decbin(myip2long($network[0]));
$cidr = $network[1];
if (substr($net_addr, 0, $cidr) == substr($ip_addr, 0, $cidr)) {
$match = 1;
break;
}
}
}
return $match;
}
$user_ip = $_SERVER['REMOTE_ADDR'];
if (ipfilter($user_ip) == 1) echo "<br />allowed! Your IP is a United States IP!";
else echo "deny!";
An example file (like the one in the example above) is available here
http://www.ipdeny.com/ipblocks/data/countries/us.zone
Not sure if the code above is correct, I got it from here'
http://www.php.net/manual/en/function.ip2long.php#86793
Probably you should add some debug code, just to understand what is going on.
Just like this:
if (substr($net_addr, 0, $cidr) == substr($ip_addr, 0, $cidr)) {
echo "My IP: $ip\n";
echo "IP to check: $network[0]\n";
echo "CIDR: $cidr\n"
echo "ip digits, my: $ip_addr, check: $net_addr\n";
$match = 1;
break;
}
So you'll see what is going wrong.