Tag Archive for String

Cut HTML string

<?php

/*
In PHP, it is easy to extract an excerpt of a text string with a given length limit. But if you want to extract an excerpt from HTML, the tags that may exist in the text string make it more complicated.

This class provides a solution to extract excerpts from HTML documents with a given text length limit without counting the length of any HTML tags.

*/
// Author prajwala
// email  m.prajwala@gmail.com
// Date   12/04/2009
// version 1.0

class HtmlCutString{
  function __construct($string, $limit){
    // create dom element using the html string
    $this->tempDiv = new DomDocument;
    $this->tempDiv->loadXML('<div>'.$string.'</div>');
    // keep the characters count till now
    $this->charCount = 0;
    $this->encoding = 'UTF-8';
    // character limit need to check
    $this->limit = $limit;
  }
  function cut(){
    // create empty document to store new html
    $this->newDiv = new DomDocument;
    // cut the string by parsing through each element
    $this->searchEnd($this->tempDiv->documentElement,$this->newDiv);
    $newhtml = $this->newDiv->saveHTML();
    return $newhtml;
  }

  function deleteChildren($node) {
    while (isset($node->firstChild)) {
      $this->deleteChildren($node->firstChild);
      $node->removeChild($node->firstChild);
    }
  } 
  function searchEnd($parseDiv, $newParent){
    foreach($parseDiv->childNodes as $ele){
    // not text node
    if($ele->nodeType != 3){
      $newEle = $this->newDiv->importNode($ele,true);
      if(count($ele->childNodes) === 0){
        $newParent->appendChild($newEle);
        continue;
      }
      $this->deleteChildren($newEle);
      $newParent->appendChild($newEle);
        $res = $this->searchEnd($ele,$newEle);
        if($res)
        return $res;
        else{
        continue;
        }
    }

    // the limit of the char count reached
    if(mb_strlen($ele->nodeValue,$this->encoding)   $this->charCount >= $this->limit){
      $newEle = $this->newDiv->importNode($ele);
        $newEle->nodeValue = substr($newEle->nodeValue,0, $this->limit - $this->charCount);
        $newParent->appendChild($newEle);
        return true;
    }
    $newEle = $this->newDiv->importNode($ele);
    $newParent->appendChild($newEle);
    $this->charCount  = mb_strlen($newEle->nodeValue,$this->encoding);
    }
    return false;
  }
}

function cut_html_string($string, $limit){
  $output = new HtmlCutString($string, $limit);
  return $output->cut();
}

?>

source

Strip spaces from a String with RegEx

// strip spaces from oldString

var newString:String = String(oldString.replace( /s/g, "" ));

source

Array Add Sufffix

function array_add_value_suffix($array, $suffix) {
foreach($array as $key => $value) {
$array[$key] = $value.$suffix;
}

return $array;
}

source

CodeIgniter Alternator

<li <?=alternator("", "class='alt'")?>>

source

Grep for files that do not match a pattern

grep -L "the pattern" *

# to recurse into subdirectories

grep -RL "the pattern" *

source

if a string contains another string

Check for string inside a string

Assumptions:

Let's have one string called $haystack which holds the value of "mother". Then, we assume another string called $needle which holds the value of "other".

What we are doing:

We want the computer to tell us whether the $haystack mother includes the word other.
How to check if PHP string contains another string

Often, we see two approaches for this. One option is to use the strpos PHP function. The following example shows how this is used:

<?php
$pos = strpos($haystack,$needle);

if($pos === false) {
// string needle NOT found in haystack
}
else {
// string needle found in haystack
}
?>

Watch out, checking for substring inside string in PHP can be tricky. Some people do just something like

if ($pos > 0) {}

or perhaps something like

if (strpos($haystack,$needle)) {
// We found a string inside string
}

and forget that the $needle string can be right at the beginning of the $haystack, at position zero. The

if (strpos($haystack,$needle)) { }

code does not produce the same result as the first set of code shown above and would fail if we were looking for example for "moth" in the word "mother".
Php string contains substring

Another option is to use the strstr() function. A code like the following could be used:

if (strlen(strstr($haystack,$needle))>0) {
// Needle Found
}

Note, the strstr() function is case-sensitive. For a case-insensitive search, use the stristr() function.
Which "find substring in a string" method is better?

The strpos() function approach is a better way to find out whether a string contains substring PHP because it is much faster and less memory intensive.
Any word of caution when checking for a substring inside string?

If possible, it is a good idea to wrap both $haystack and $needle with the strtolower() function. This function converts your strings into lower case which helps to eliminate problems with case sensitivity.

source

Fuzzy string matching with Perl

use String::Approx 'amatch';
use Test::More(no_plan);

sub fuzm {

$_ = shift;

return amatch("homer_simpson", [        # this array sets match options:
"i",    # match case-insensitively
"10%",  # tolerate up to 1 character in 10 being wrong
"S0",   # but no substituting one character for another
"D1",   # although, tolerate up to one deletion
"I2"    # and tolerate up to two insertions
]);

}

ok(fuzm("homer_simpson"),         "exact match for 'homer_simpson'");
ok(fuzm("homersimpson"),          "still matches without the underscore");
ok(fuzm("homers_impson"),         "putting the underscore in a different place, still matches");
ok(fuzm("ho_mer_simpson"),        "an extra underscore still matches");
ok(fuzm("ho_mer_simp_son"),       "2 extra underscores still matches");
ok((not fuzm "ho_mersimp_son"),   "2 underscores, both in the wrong places, doesn't match");
ok((not fuzm "ho_mer_sim_ps_on"), "3 extra underscores doesn't match");
ok((not fuzm "homer____simpson"), "3 extra underscores doesn't match");

source

Ordenar un query por longitud de una cadena

SELECT ... ORDER BY LENGTH(your_field);

source

Truncate a string to a set length, breaking at word boundaries

/**
* Author: Andrew Hedges, <a href="mailto:andrew@hedges.name">andrew@hedges.name</a>
* License: free to use, alter, and redistribute without attribution
*/

/**
* Truncate a string to the given length, breaking at word boundaries and adding an elipsis
* @param string str String to be truncated
* @param integer limit Max length of the string
* @return string
*/
var truncate = function (str, limit) {
var bits, i;
if (STR !== typeof str) {
return '';
}
bits = str.split('');
if (bits.length > limit) {
for (i = bits.length - 1; i > -1; --i) {
if (i > limit) {
bits.length = i;
}
else if (' ' === bits[i]) {
bits.length = i;
break;
}
}
bits.push('...');
}
return bits.join('');
};
// END: truncate

source

Get Day Suffix

def getDaySuffix(dayNumber):
if dayNumber <= 3:
return {1:"st", 2:"nd", 3:"rd"}[dayNumber]
else:
return "th"

# ex: June 12th
nowTime = datetime.datetime.now()
print nowTime.strftime("%B %d" + getDaySuffix(nowTime.timetuple()[2]))

source