5
I’m not getting to use the function preg_split()
correctly.
I’m trying to break a string array()
via regex but it’s not happening.
$string = "<:termo.9:><:termo.10:><:termo.11:>";
$res = preg_split("/(<:)(nome|termo)(.)(\d+)(:>)/", $string,-1,PREG_SPLIT_DELIM_CAPTURE);
The value attributed to $res
is:
Array (
[0] =>
[1] => <:
[2] => termo
[3] => .
[4] => 9
[5] => :>
[6] =>
[7] => <:
[8] => termo
[9] => .
[10] => 12
[11] => :>
[12] =>
[13] => <:
[14] => termo
[15] => .
[16] => 10
[17] => :>
[18] =>
[19] => <:
[20] => termo
[21] => .
[22] => 11
[23] => :>
)
And I’d actually like to:
Array (
[0] => "<:termo.9:>"
[1] => "<:termo.10:>"
[2] => "<:termo.11:>"
)
A palliative solution would be to use the following Pattern:
$res = preg_split("/(<:nome\.\d+:>|<:termo\.\d+:>)/", $string,-1,PREG_SPLIT_DELIM_CAPTURE);
And the $res
sai:
Array (
[0] =>
[1] => <:termo.9:>
[2] =>
[3] => <:termo.12:>
[4] =>
[5] => <:termo.10:>
[6] =>
[7] => <:termo.11:>
[8] =>
[9] => <:termo.9:>
[10] =>
)
But if you look closely, the conditions imposed are:
(<:nome\.\d+:>|<:termo\.\d+:>)
And the variations of nomenclatures that I can use can increase, like:
<:name.2:>, <:text.4:>,<:code.5:>,etc
and this way the code would not be "optimized", say so.
What could be wrong in Pattern for it to be improved?
Have you tried putting in the 4th parameter
preg_split_delim_capture
?– Wallace Maxters
@Wallacemaxters really returned the
array
breaking the String, but broke every condition of thepattern
. Ex:Array([0]=>"<:",[1]=>"nome",[2]=>"."...etc)
– thelimarenan
It is practically impossible to do this using the
preg_split
, because, this function looks for specific references to split the code. It’s practically an improved version ofexplode
, if I may say so.– Edilson
@Edilson I think I understand better now. Maybe the solution I need is not to use
preg_split
.– thelimarenan