PHP

Check if string is UTF-8

Have not tested it...

function check_utf8($str) {
$len = strlen($str);
for($i = 0; $i < $len; $i++){
$c = ord($str[$i]);
if ($c > 128) {
if (($c > 247)) return false;
elseif ($c > 239) $bytes = 4;
elseif ($c > 223) $bytes = 3;
elseif ($c > 191) $bytes = 2;
else return false;
if (($i + $bytes) > $len) return false;
while ($bytes > 1) {
$i++;
$b = ord($str[$i]);
if ($b < 128 || $b > 191) return false;

Find the boundary of a word that starts åäö

This is how you find a whole word by its boundary when the word is starting with åäö. The usual boundary expression can handle if Swedish characters is in the string but not if it starts (or ends) the word. That means that a word like "öknen" can't be found but a word like "behöver" will be found.

<?php
$text
= "I öknen behöver man vatten";
$keyword = "öknen";
//$keyword = "behöver";
?>

This is the usual boundary expression

How to find exact match of word in a string

This is how you find an exact word in some text string. The "\b" is for finding the words boundary and the "i" is to let the search be case insensitive.

<?php

$matches
= array();
$text = "Play poker"; //Some text
$keyword = "Poker";
   
preg_match("/\b".$keyword."\b/i", $text, $matches, PREG_OFFSET_CAPTURE);
       
foreach (
$matches as $key => $value) {
  echo
"<br>$key => $value";
}
?>


Array
(
    [0] => Array
        (
            [0] => poker
            [1] => 5
        )

)

PHP array first or last of key or value

Here's how to get the first key, the last key, the first value or the last value of a (hash) array without explicitly copying nor altering the original array:


<?php
  $array
= array('first'=>'111', 'second'=>'222', 'third'=>'333');

 
// get the first key: returns 'first'
 
print array_shift(array_keys($array));

 
// get the last key: returns 'third'
 
print array_pop(array_keys($array));

 
// get the first value: returns '111'
 
print array_shift(array_values($array));

 
// get the last value: returns '333'
 
print array_pop(array_values($array));
?>

Sort a multidimensional array based on given key value

How to sort a multidimensional array based on a given key value.


/**
* Sort an array based on a given field key
*
* @param unknown_type $named_recs
* @param unknown_type $order_by
* @param unknown_type $rev
* @param unknown_type $flags
* @return unknown
*/
function _named_records_sort($named_recs, $order_by, $reverse=false, $flags=0) {
// Create 1-dimensional named array with just sortfield (in stead of record) values
$named_hash = array();
foreach($named_recs as $key=>$fields)
$named_hash["$key"] = $fields[$order_by];

// Or

Pages