note 89649 added to function.preg-split
| From: | csaba at alum dot mit dot edu | Date: | Tue, 17 Mar 2009 21:06:20 +0000 |
| Subject: | note 89649 added to function.preg-split | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-152067@lists.php.net to get a copy of this message | ||
If the task is too complicated for preg_split, preg_match_all might come in handy, since preg_split
is essentially a special case.
I wanted to split a string on a certain character (asterisk), but only if it wasn't escaped (by
a preceding backslash). Thus, I should ensure an even number of backslashes before any asterisk
meant as a splitter. Look-behind in a regular expression wouldn't work since the length of the
preceding backslash sequence can't be fixed. So I turned to preg_match_all:
<?php
// split a string at unescaped asterisks
// where backslash is the escape character
$splitter = "/\\*((?:[^\\\\*]|\\\\.)*)/";
preg_match_all($splitter, "*$string", $aPieces, PREG_PATTERN_ORDER);
$aPieces = $aPieces[1];
// $aPieces now contains the exploded string
// and unescaping can be safely done on each piece
foreach ($aPieces as $idx=>$piece)
$aPieces[$idx] = preg_replace("/\\\\(.)/s", "$1", $piece);
?>
----
Server IP: 81.223.48.75
Probable Submitter: 80.108.23.194
----
Manual Page -- http://www.php.net/manual/en/function.preg-split.php
Edit -- https://master.php.net/note/edit/89649
Del: integrated -- https://master.php.net/note/delete/89649/integrated
Del: useless -- https://master.php.net/note/delete/89649/useless
Del: bad code -- https://master.php.net/note/delete/89649/bad+code
Del: spam -- https://master.php.net/note/delete/89649/spam
Del: non-english -- https://master.php.net/note/delete/89649/non-english
Del: in docs -- https://master.php.net/note/delete/89649/in+docs
Del: other reasons-- https://master.php.net/note/delete/89649
Reject -- https://master.php.net/note/reject/89649
Search -- https://master.php.net/manage/user-notes.php