PHP: preg_split - Manual
vendredi 23 août 2019 à 07:53OMAGAD Il existe une fonction comme explode mais qui utilise les regex : preg_split !
// scinde la phrase grâce aux virgules et espacements
// ce qui inclus les " ", \r, \t, \n et \f
$keywords = preg_split("/[\s,]+/", "langage hypertexte, programmation");
print_r($keywords);
// retour:
Array
(
[0] => langage
[1] => hypertexte
[2] => programmation
)
et peut même renvoyer la position de chaque morceau dans la chaîne d'origine:
$str = 'langage hypertexte, programmation';
$chars = preg_split('/ /', $str, -1, PREG_SPLIT_OFFSET_CAPTURE);
// retour:
Array
(
[0] => Array
(
[0] => langage
[1] => 0
)
[1] => Array
(
[0] => hypertexte,
[1] => 8
)
[2] => Array
(
[0] => programmation
[1] => 20
)
)
... voire même virer automatiquement les chaînes vides avec le flag PREG_SPLIT_NO_EMPTY
Reste plus qu'à benchmarquer pour voir si c'est pas trop gourmand par rapport à explode.
<link rel="stylesheet" href="http://www.warriordudimanche.net/./plugins/Galart/style.css"/> <link rel="stylesheet" href="http://www.warriordudimanche.net/./plugins/Galart/assets/lightbox.css"/> <script src="http://www.warriordudimanche.net/./plugins/Galart/assets/lightbox.js"> <script>[].forEach.call(document.querySelectorAll("[lightbox]"), function(el) { el.lightbox = new Lightbox(el);});► Commentaires