P
P
PO6OT2015-10-20 17:06:25
PHP
PO6OT, 2015-10-20 17:06:25

How to use escaping when explode?

Suppose there is such a line:
type\:text:content\:some_data
It is formed like this:

$in[]='type:text';
$in[]='content:some_data';
for($i=0; isset($in[$i]); $i++){
 $in[$i]=str_replace(array('\', ':'), array('\\', '\:'), $in[$i]);
}
$string=implode(':', $in); //$string=='type\:text:content\:some_data'

You need to split the string on the separator ":", taking into account the escaping.
explode() will split the string like this:
1. type\
2. text
3. content\
4. some_data
but you must
1. type:text
2. content:some_data

How to do it?

Answer the question

In order to leave comments, you need to log in

3 answer(s)
P
PO6OT, 2015-10-20
@woonem

en.stackoverflow.com/questions/208329/%D0%A0%D0%B0...

function custom_split($str) {
    $parts = preg_split('/(?<![^\\\\]\\\\):/', $str);
    array_walk($parts, function(&$v) { $v = str_replace('\\:', ':', $v); });

    return $parts;
}

var_dump(custom_split('a:b:c:d\\:h:g'));
var_dump(custom_split('a:b:c:d\\\\:h:g'));

> array (size=5)
>   0 => string 'a' (length=1)
>   1 => string 'b' (length=1)
>   2 => string 'c' (length=1)
>   3 => string 'd:h' (length=3)
>   4 => string 'g' (length=1)
> array (size=6)
>   0 => string 'a' (length=1)
>   1 => string 'b' (length=1)
>   2 => string 'c' (length=1)
>   3 => string 'd\\' (length=3)
>   4 => string 'h' (length=1)
>   5 => string 'g' (length=1)

G
GreatRash, 2015-10-20
@GreatRash

Why not split on "\:" ?

M
Mikhail Osher, 2015-10-20
@miraage

Then dance yourself.

$input = 'type\:text:content\:some_data';
$output = preg_split('/(?<!\\\\):/', $input);

var_dump($output);

array(2) {
  [0] =>
  string(10) "type\:text"
  [1] =>
  string(18) "content\:some_data"
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question