niknik90
niknik90

Reputation: 53

Split php string only after symbol

Hi everybody i need some help, im new in php. I have a string like this

$string="+note1-note2-note3+note4-note5-note6+note7-note8-note10";

I need to extract to array only the part with + like: note1, note4, note7.

Can someone help me? Thanks so much!!

Upvotes: 1

Views: 81

Answers (1)

chris85
chris85

Reputation: 23892

You can do this pretty easily with a regex.

$string="+note1-note2-note3+note4-note5-note6+note7-note8-note10";
preg_match_all('/\+(note\d+)/', $string, $matches);
print_r($matches[1]);

Output:

Array
(
    [0] => note1
    [1] => note4
    [2] => note7
)

Regex101 Demo: https://regex101.com/r/pW3eS0/1

\d is a number and the second + is a quantifier meaning 1 or more of the preceding character/group. The first plus \+ is literal, the preceding \ makes it the actual + character, otherwise it would cause an error because it would be the quantifier but be quantifying nothing.

PHP Demo: https://eval.in/527661

Upvotes: 3

Related Questions