put comma in alexa rank - php

I have alexa function and return alexa rank. I want to put comma in every three digit.
ex: 1,500,500
I have tried to use number_format() but it doesn't work with me. here is the function
<?php
/**
* Get Popularity Text of a Domain via Alexa XML Data
*
* #return string|FALSE text or FALSE on error
*/
function alexa_get_rank($domain)
{
$alexa = "http://data.alexa.com/data?cli=10&dat=s&url=%s";
$request_url = sprintf($alexa, urlencode($domain));
$xml = simplexml_load_file($request_url);
if (!$xml) {
return FALSE;
}
$nodeAttributes = $xml->SD[1]->POPULARITY->attributes();
$text = (int) $nodeAttributes['TEXT'];
$num = number_format($text);
return $num;
}
this only returns 3 numbers
ex: ranks is 1,500,500 but it shows 500 only.
thank you

Quick and dirty answer:
try to define all the params of number format, for what I know it should work.
At last, if nothign else works you don't need to use the regex, just juggle with the string version of your number:
function addCommas($number) {
return strrev(join(",",str_split(strrev($number),3)));
}
After a short test session on codepad I can assure to you that you code should work as is,
at http://codepad.org/0zLuBQp8 you will find a slightly modified demo (I've retrieved data with a query and pasted the xml as string to circumvent some codepad limitations).
(I would suggest you to split the xml loading phase in two in order to check if your input is healty and you are manipulating the right datas)

You could always run a simple while statement::
$text = (int) $nodeAttributes['TEXT'];
while (true){
$num = preg_replace('/(-?\d+)(\d\d\d)/', '$1,$2', $text );
if ($num != $text ) {
$text = $num;
} else {
break;
}
}
return $num;

Related

What Algorithm is used for this?

im doing research project for a the game Text twist,the text will automatically search word from a dictionary and scramble then, and also process the words to be found automatically using the same concept with this site http://grecni.com/texttwist.php , i also need to provide an algorithm that i will use for my project,and im planning to include this word unscrambler in this web site http://grecni.com/texttwist.php but i dont know what algorithm is possibly use to do the actions done on the website i posted. does any one know what type, or what you call the algorithm used,or can be use that will give the same results, an example of the algorithm will be greatly appreciated.
The data structure you want is called a Directed Acyclic Word Graph (dawg)
There are questions already answered about this:
Algorithm to get a list of all words that are anagrams of all substrings (scrabble)?
Writing an algorithm for scrabble
You could also perhaps implement the levenshtein algorithm which would accomplish pretty much the same result:
MySQL - Which Hash Algo should I use for this?
Update:
After giving myself a challenge to create an example to demonstrate the algorithm ive come up with this, as its from a plugin built for my cms its wrapped in a class but your get the idea there is a demo # http://cherone.co.uk/scrabble_suggest
First I created a table with id,word,sorted (word = the actual word, sorted = the word alphabetically sorted like for e.g: aardvark sorted would be aaadkrrv) i just found an english wordlist on the internets.
The form posts the string and then the string is sorted alphabetically to match 1:1 the sorted column, then the string is split into each character and then queried sequentially till the last character. The functions of interest are str_sort,permute,swap Perhaps its of some interest..
<?php
/**
* Scrabble solver Plugin this file is "inline" included within the frontController class
*/
Class plugin{
function __construct($core) {
$this->core = $core;
$this->plugin_path = SITE_ROOT.'/core/plugins/'.$this->core->router->action.'/';
$this->request = explode('/',$this->core->router->request);
//Assign Page meta tags ect
$this->core->template->meta_keywords = 'Text,Twist,Text Twist,word,letter,scrabble,unscrambler,unscramble,word finder,puzzle,anagram,scrabble,cheat,cheater,help,helper,solve,solver,free,php';
$this->core->template->meta_description = 'Scrabble and Anagram like word solver tool to help unscramble letters and words and cheat at your favorite word puzzle';
$this->core->template->page_title = $this->core->template->site_name." - Scrabble and Anagram like word solver";
$route = (isset($this->request[2])?$this->request[2]:null);
}
function load(){
set_time_limit(0);
$data=array('var'=>$this,'result'=>'','word'=>'','word_sort'=>'');
switch($this->core->router->subaction){
case "index":
$string='';
if($_SERVER['REQUEST_METHOD']=='POST'){
$string = substr(preg_replace('/[^a-zA-Z]/s', '', trim(strtolower($_POST['letters']))),0,8);
$data['word'] = $string;
$string = $this->str_sort($string);
$data['word_sort'] = $string;
}
$stringLen = strlen($string);
$result = array();
for($i=2;$i<=$stringLen;$i++){
$seq = substr($data['word_sort'],0,$i);
$rounds = explode('|',$this->permute($seq,0,strlen($seq)));
$r=$i;
foreach($rounds as $round){
$result[$r] = $this->get_words($round,strlen($seq));
$r++;
}
}
$data['result'] = $result;
$this->core->template->content_center = $this->core->template->loadContentView(get_class(),$this->core->router->subaction,$data);
$this->core->template->content_left = '';
$this->core->template->content_right = '';
break;
case "update":
$this->insert_word_lists();
header('Location: '.SITE_URL.'/'.$this->core->router->action);
die;
break;
case "api":
header('Content-Type: application/json');
echo 'No api for this plugin, perhaps one comming soon. ;p';
break;
default:
header('Location: '.SITE_URL.'/'.$this->core->router->action);
die;
break;
}
}
//Query Method to search for sequenced alphabetically sorted words.
private function get_words($word,$stringLen){
$chars = str_split($word,1);
$sql = "SELECT DISTINCT `word` FROM `plugin_scrabble_words` WHERE ";
foreach($chars as $char){
$sql .=' `sorted` LIKE "%'.$char.'%" AND';
}
$sql = trim($sql,'AND');
$sql .= ' AND LENGTH(sorted) = '.$stringLen;
$statement = $this->core->db->prepare($sql);
$statement->execute();
$result = $statement->fetchAll(PDO::FETCH_ASSOC);
return $result;
}
//A Model method for updating the database word list.
private function insert_word_lists(){
set_time_limit(0);
$lists = glob($this->plugin_path."wordlists/*.txt");
foreach ($lists as $list){
$words = file($list);
foreach($words as $word){
$word = strtolower(preg_replace('/[^a-zA-Z]/s', '', $word));
if($this->sql_check_word($word)===false){
$this->sql_put_word($word);
}
}
}
}
//A Model method for checking the database specific word.
private function sql_check_word($word){
$sql = "SELECT `word` FROM `plugin_scrabble_words` WHERE `word` = :word";
$statement = $this->core->db->prepare($sql);
$statement->bindParam(':word', $word, PDO::PARAM_STR);
$statement->execute();
$result = $statement->fetchAll(PDO::FETCH_ASSOC);
if(!empty($result)){
return true;
}else{
return false;
}
}
//A Model method for adding the word to the database.
private function sql_put_word($word){
$sql = "INSERT into `plugin_scrabble_words` (word,sorted) VALUES (:word,:sorted)";
$statement = $this->core->db->prepare($sql);
$sorted = $this->str_sort($word);
$statement->bindParam(':word', $word, PDO::PARAM_STR);
$statement->bindParam(':sorted', $sorted, PDO::PARAM_STR);
$statement->execute();
}
//Sort Method that will sort a sring in alphabetical order
private function str_sort($string) {
$tmp = str_split($string);
sort($tmp);
return implode('',$tmp);
}
//Method to generate and return all permutations of the string with | delimiter.
private function permute($str,$i,$n) {
if ($i == $n){
return $str.'|';
} else {
for ($j = $i; $j < $n; $j++) {
$this->swap($str,$i,$j);
$this->permute($str, $i+1, $n);
$this->swap($str,$i,$j);
}
}
}
//Method to swap the char at pos $i and $j of $str.
private function swap(&$str,$i,$j) {
$temp = $str[$i];
$str[$i] = $str[$j];
$str[$j] = $temp;
}
}
?>
One approach would be to generate all possible permutations of the letters and match them against a dictionary. For an N lettered character sequence, this would take O(N!) time if you keep the dictionary in a set data structure.
For shorter sequences (10 characters or so), this is a perfectly good strategy.
For longer sequences, you should do the reverse. You can loop through the dictionary and determine if your character sequence has the characters to make the word. For M dictionary elements, this would take more or less O(M) time. There are various ways you can speed up this technique like pre-computing the number of each letter in each dictionary entry.
edit: The gentleman below me gives a more algorithmically rigorous and thorough treatment of the subject, and so I would direct you to his explanation (which employs big O notation which mine... embarrassingly does not).
Actually, although VanDang called it a "naive approach", there's nothing wrong with testing all possible combinations of the finite set of characters given. As long as a person is prevented from providing an arbitrary number of characters, there is a maximum of !n combinations of letters (with n = the number of letters, assuming there are no repeats), and, since words in English don't get THAT long, testing each combination wouldn't be that bad.
After all, the method of exhaustion is actually an accepted method for optimizing large boolean expressions when generating hardware descriptions.

Comparing two Arabic-language string values in PHP?

I'm having problems trying to compare two Arabic-language strings in a PHP script to see if they match. I've tried setting the internal encoding to UTF-8 with mb_internal_encoding, I've tried a simple if ($x == $y) expression, I've tried strcmp()... no dice. Any idea what I'm doing wrong? Does PHP have problems with doing string comparisons with non-English text?
Thanks!
Here is a code excerpt:
// Chop up HTML content into bits
$threadPieces = explode('</div>', $innerHTML);
// Chop up the HTML bits into data entries
$strippedThreadPieces = strip_tags($threadPieces[1]);
$threadInfo = explode('-', $strippedThreadPieces);
$threadTitleExists = trim($threadTitleExists, 'thread_title_');
$postername = "مراسل";
if (($threadTitleExists > 100000) && ($threadInfo[0] === $postername))
{
echo 'Thread title:';
echo strip_tags($threadPieces[0]);
echo '<p>';
}
else
{
}
I think the problem is the character set of your php file, try to save it using utf-8 character set.
The way I did this was using the function mb_ereg which is regular expression match with multibyte support.
Here's one I'm using
//from http://www.phperz.com/article/14/1029/31806.html
function mb_split_str($str) {
preg_match_all("/./u", $str, $arr);
return $arr[0];
}
//based on http://www.phperz.com/article/14/1029/31806.html, added percent
function mb_similar_text($str1, $str2, &$percent) {
$arr_1 = array_unique(mb_split_str($str1));
$arr_2 = array_unique(mb_split_str($str2));
$similarity = count($arr_2) - count(array_diff($arr_2, $arr_1));
$percent = ($similarity * 200) / (strlen($str1) + strlen($str2) );
return $percent;
}
So
$var = mb_similar_text('عمار', 'ياسر', $per);
output: $var = 2, $per = 25

MySQL / PHP, but more of a MATH Question (Shortening Script)

For my latest project I need to shorten the URLs which I then put in a mysql database.
I now ran against a problem, because I don't know how to solve this. Basically, the shortened strings should look like this (I want to include lowercase letters, uppercase letters and numbers)
a
b
...
z
0
...
9
A
...
Z
aa
ab
ac
...
ba
So, 1. URl --> a. Stored in mysql.
Next time, a new url gets stored to --> b because a is already in the mysql database.
And that is it. But I don't have any idea. Could someone of you please help me out?
Edit: Formattted & Further explanation.
It is kinda like the imgur.com URL shortening service. It should continue like this until infinity (which is not needed, I think...)
You can use the following function (code adapted from my personal framework):
function Base($input, $output, $number = 1, $charset = 'abcdefghijklmnopqrstuvwxyz0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ')
{
if (strlen($charset) >= 2)
{
$input = max(2, min(intval($input), strlen($charset)));
$output = max(2, min(intval($output), strlen($charset)));
$number = ltrim(preg_replace('~[^' . preg_quote(substr($charset, 0, max($input, $output)), '~') . ']+~', '', $number), $charset[0]);
if (strlen($number) > 0)
{
if ($input != 10)
{
$result = 0;
foreach (str_split(strrev($number)) as $key => $value)
{
$result += pow($input, $key) * intval(strpos($charset, $value));
}
$number = $result;
}
if ($output != 10)
{
$result = $charset[$number % $output];
while (($number = intval($number / $output)) > 0)
{
$result = $charset[$number % $output] . $result;
}
$number = $result;
}
return $number;
}
return $charset[0];
}
return false;
}
Basically you just need to grab the newly generated auto-incremented ID (this also makes sure you don't generate any collisions) from your table and pass it to this function like this:
$short_id = Base(10, 62, $auto_increment_id);
Note that the first and second arguments define the input and output bases, respectively.
Also, I've reordered the charset from the "default" 0-9a-zA-Z to comply with your examples.
You can also just use base_convert() if you can live without the mixed alphabet case (base 36).

Turning an integer into random string and back again

what I'm wanting is to convert an integer into a string. For example, 123456789 may become 8GFsah93r ... you know like Youtube, Pastebin and what not. I then want to convert it back.
I'm working with large integers, for example: 131569877435989900
Take a look at this link: http://codepad.viper-7.com/wHKOMi
This is my attempt using a function I found on the web, obviously... it's not correctly converting back to integer. I'm needing something that does this realiably.
Thanks
Ok, one of the ideas is to use a character array as a representation of a numeric system. Then you can convert from base 10 to base x and vica-versa. The value will be shorter and less readable (altought, you should encrypt it with a two-way crypter if it must be secure).
A solution:
final class UrlShortener {
private static $charfeed = Array(
'a','A','b','B','c','C','d','D','e','E','f','F','g','G','h','H','i','I','j','J','k','K','l','L','m',
'M','n','N','o','O','p','P','q','Q','r','R','s','S','t','T','u','U','v','V','w','W','x','X','y','Y',
'z','Z','0','1','2','3','4','5','6','7','8','9');
public static function intToShort($number) {
$need = count(self::$charfeed);
$s = '';
do {
$s .= self::$charfeed[$number%$need];
$number = floor($number/$need);
} while($number > 0);
return $s;
}
public static function shortToInt($string) {
$num = 0;
$need = count(self::$charfeed);
$length = strlen($string);
for($x = 0; $x < $length; $x++) {
$key = array_search($string[$x], self::$charfeed);
$value = $key * pow($need, $x);
$num += $value;
}
return $num;
}
}
Then you can use:
UrlShortener::intToShort(2);
UrlShortener::shortToInt("b");
EDIT
with large numbers, it does not work. You should use this version (with bcmath http://www.php.net/manual/en/book.bc.php ) with very large numbers:
final class UrlShortener {
private static $charfeed = Array(
'a','A','b','B','c','C','d','D','e','E','f','F','g','G','h','H','i','I','j','J','k','K','l','L','m',
'M','n','N','o','O','p','P','q','Q','r','R','s','S','t','T','u','U','v','V','w','W','x','X','y','Y',
'z','Z','0','1','2','3','4','5','6','7','8','9');
public static function intToShort($number) {
$need = count(self::$charfeed);
$s = '';
do {
$s .= self::$charfeed[bcmod($number, $need)];
$number = floor($number/$need);
} while($number > 0);
return $s;
}
public static function shortToInt($string) {
$num = 0;
$need = count(self::$charfeed);
$length = strlen($string);
for($x = 0; $x < $length; $x++) {
$key = array_search($string[$x], self::$charfeed);
$value = $key * bcpow($need, $x);
$num += $value;
}
return $num;
}
}
$original = 131569877435989900;
$short = UrlShortener::intToShort($original);
echo $short;
echo '<br/>';
$result = UrlShortener::shortToInt($short);
echo $result;
echo '<br/>';
echo bccomp($original, $result);
If something missing from here, please let me know, because it's only a snippet from my library (I don't wanna insert the whole thing here)
negra
check base64 encoding: http://php.net/manual/en/function.base64-encode.php http://php.net/manual/en/function.base64-decode.php
If you want a shorter string first encode it into an 8bit string then encode. You can do this with % 256 and / 256.
Or you could manually do what base64 does, get the first 6bits and encode it to a char.
Why not use something like this? Do you need it heavily encrypted?
$num = 131569877435989900;
echo $str = base64_encode($num);
echo base64_decode($str);
I think what you want is to encode the ids using Base32. The resulting string contains only the 26 letters of the alphabet and the digits 2-7, making it very human readable.
The simplest would be to use something like base_convert -- unfortunately, it won't work for such large integers correctly.
However, you can use the same idea by copying base_convert_arbitrary from my answer here and doing:
$id = '131569877435989900';
$encoded = base_convert_arbitrary($id, 10, 36);
$decoded = base_convert_arbitrary($encoded, 36, 10);
print_r($encoded);
print_r($decoded);
See it in action.
The nice thing about this approach is that you can tweak the first line inside the function, which reads:
$digits = '0123456789abcdefghijklmnopqrstuvwxyz'; // 36 "digits"
Add any other "digits" you find acceptable (e.g. capital letters or other symbols you don't mind having in your URL). You can then replace the base 36 in the above example with a larger one (you can go as high as there are defined digits), and it will work just like you want it to.
See it here working with 62 digits.
I am suprised No one is mentioning base64_encode() and it partner base64_decode().
If you were not considering length this is perfect
$before = base64_encode(131569877435989900);
$after = 'MS4zMTU2OTg3NzQzNTk5RSsxNw==';
$on_reverse = base64_decode('MS4zMTU2OTg3NzQzNTk5RSsxNw==');
$on_reverse == 131569877435989900;
I always go for the simplest solutions, as long as they don't compromise my security.
The easiest way to get random string is to use hash functions like md5() or sha1() For example:
<?php
$bigInt = '131569877435989900';
$hash = md5($bigInt);
$hashed=substr($hash,0,-20);
echo $hashed;
?>
These hash functions are irreversible-you can't get the original value(these functions are also used to crypt data). If you want you can save the original big integer in an array or a database. But decripting the hash would be impossible.

PHP Simple Spell Checker (Binary Search help)

I need help with performing a binary search with a search term ($searchTerm) and comparing it to a dictionary ($dictionary).
Basically, it reads a dictionary file into an array. The user inputs some words, that string becomes $checkMe. I do an explode function and it turns into $explodedCheckMe. I pass each term in $checkMe to binarySearch as $searchTerm (Okay, my code is confusing). I think my logic is sound, but my syntax isn't ...
I've been using this a lot: http://us3.php.net/manual/en/function.strcasecmp.php
here is my code: paste2.org/p/457232
I know this doesn't directly answer your question, but have you considered using pspell and a custom dictionary?
So you are looking up exact strings in the dictionary. Why don't you a simple array for this? The native PHP's hash table is definitely going to be faster than a binary search implemented in PHP.
while (!feof($file)) {
$dictionary[strtolower(fgets($file))] = 1;
}
...
function search($searchTerm, $dictionary) {
if ($dictionary[strtolower($searchTerm)]) {
// do something
}
}
But if you really want to use a binary search, try this:
function binarySearch($searchTerm, $dictionary) {
$minVal = 0;
$maxVal = count($dictionary);
while ($minVal < $maxVal) {
$guess = intval($minVal + ($maxVal - $minVal) / 2);
$result = strcasecmp($dictionary[$guess], $searchTerm);
if ($result == 0) {
echo "FOUND";
return;
}
elseif ($result < 0) {
$minVal = $guess + 1;
}
else {
$maxVal = $guess;
}
}
}
The main problem was that you can't set $maxval to $guess - 1. See the wikipedia article on binary search, it's really good.

Categories