Articles

The month of PHP functions : regex slicing

  • Ecrit par Julien Pauli
  • mardi 24 avril 2007
Image pour le titre du contenu

Ce document est aussi disponible en français fr 


preg_split() slice a string using a regular expression. It is the same functionnality than the one provided by explode() and str_split(), execpt that preg_split() uses the regex engine, and it is more powerful and slower.

Example 1 - Counting words in a sentence :

<?php
 
function FindMots($s){
 
      $p=preg_split("/\s+/",$s);
 
      foreach($p as $w){
 
          $a[strtolower($w)]++;
 
      }
 
      return $a;
 
  }
 
 
 
  $s='PHP langage de programmaTION Php PhP LangAgE';
 
  print_r(FindMots($s));
 
?><strong>
 
</strong>

Example 2 - Turning HTML entities to charset, with exceptions :

<?php
 
function html_convert ($string) {
 
  $out = '';
 
  $pattern = '/(<\/?(?:a .*|h1|h2|b|i|html)>)/ims';
 
  $array = preg_split( $pattern, $string, -1, PREG_SPLIT_DELIM_CAPTURE | PREG_SPLIT_NO_EMPTY );
 
  foreach ($array as $element) {
 
    if (!preg_match($pattern, $element)){
 
      $out .= htmlspecialchars ($element);
 
  }else{
 
  $out .= $element;
 
}
 
}
 
  return $out;
 
}
 
echo html_convert('<html><b>foo</b><i>bar</i>un texte hors balise<p>balis&Egrave; avec paragraphe</p><h1>et titre de forme h1</h1></html>');
 
?><strong>
 
</strong>

Example 3 - Getting mime types from a browser :

<?php
 
$mimetypes = preg_split(';[\s,]+;', substr(getenv('HTTP_ACCEPT'), 0, strpos(getenv('HTTP_ACCEPT') . ';', ';')), -1, PREG_SPLIT_NO_EMPTY);
 
// par exemple : Array ( [0] => text/xml [1] => application/xml [2] => application/xhtml+xml [3] => text/html )  
 
?><strong>
 
</strong>

Keep in mind

  • preg_split() is from the preg familyt. It uses PCRE
  • Don't use preg function wher you can do the same without the regex, like with explode() or str_split()
< Précédent   Suivant >

Commentaires

Vous pouvez ajouter votre commentaire!


Vous devez vous connecter pour commenter