M K M K - 4 months ago 7
PHP Question

segment a string to many strings given a pattern in php

I'm stuck and I just need a pointer.
I have this string with special characters retrieved from db and i want to segment it to many strings or arrays and in the process i want to exchange those characters with "()".
|p| stands for parent. |c| child.

Example sentence is :

my beautiful car is awesome


*where my , beautiful and car have a parent-child relationship.

The pattern for it :

|p|my|c||p|beautiful|c||c||p|car|p|is|p|awesome


In case you need to see the original array:

Array
(
[0] => Array
(
[name] => |p|my
[parent_id] => 0
[child] => Array
(
[0] => Array
(
[name] => |c||p|beautiful
[parent_id] => 1
[child] => Array
(
[0] => Array
(
[name] => |c||c||p|car
[parent_id] => 2
)

)

)

)

)

[1] => Array
(
[name] => |p|is
[parent_id] => 0
)

[2] => Array
(
[name] => |p|awesome
[parent_id] => 0
)

)


The ultimate goal after segmenting and replacement is:
((My(beautiful(car)) (is)(awesome))

Answer

Since you requested only a pointer I suggest to start with a regex to get an intermediate array:

$str = '|p|my|c||p|beautiful|c||c||p|car|p|is|p|awesome';
$res = preg_split('/((?:\|c\|)*\|p\|)/', $str, null, PREG_SPLIT_DELIM_CAPTURE | PREG_SPLIT_NO_EMPTY);
var_export($res);

/*
array (
  0 => '|p|',
  1 => 'my',
  2 => '|c||p|',
  3 => 'beautiful',
  4 => '|c||c||p|',
  5 => 'car',
  6 => '|p|',
  7 => 'is',
  8 => '|p|',
  9 => 'awesome',
)
*/