Trim a String Without Cutting Any Words


Sometimes you need to trim a string without cutting any word.

In PHP there is no any function for that but this function may help you.


function trim_sentence($str, $n, $delim='...'){
$len = strlen($str);
if ($len > $n){
preg_match('/(.{' . $n . '}.*?)\b/', $str, $matches);
return rtrim($matches[1]) . $delim;
}
else {
return $str;
}
}

Posted in PHP

Fetch URL Content using PHP


I recently had to develop a small script that will fetch an XML file from the web. All I had to do is download a given URL and read its contents. To my great surprise I found that download the file using my jx Ajax library was much easier than doing it with PHP.

PHP make this very easy by including functions like file_get_contents() that has URL support. This code will get you the contents of an URL.

$contents = file_get_contents('http://example.com/rss.xml');

Unfortunately, this is a huge security threat – and many servers have disabled this feature in PHP. Also this is not the most optimized method to fetch an URL. Also, it is impossible to submit data using the POST method using this function.

PHP provide other two method to fetch an URL – Curl and Fsockopen. But to use them you have to be aware about both these libraries and you need to write down a lot of code.

Finally I found on net a very cool PHP function  load() which is developed by Binny. You can visit his site

http://www.bin-co.com/php/scripts/load/

Using this load() function you can easily fetch the URL content. It returns the data as an object.

Hat’s off Binny 🙂 gud job

cheers,

jaswant