I have a string like this:
some address number 23 neighborhood city
Now, my goal is to separate it in two parts:
some address number 23
neighborhood city
I am guessing this will require a combination of the split
or preg_replace
commands using something like this /[^0-9]/
. No matter how I tried, I did not get the desired result.
Edit: There is 2 absolute correct answers, One using preg_replace and the another one preg_split, Good luck !
Advertisement
Answer
You can use preg_split() with flags (PREG_SPLIT_DELIM_CAPTURE | PREG_SPLIT_NO_EMPTY
)
<?php $word= "some address number 23 neighborhood city"; $keywords = preg_split("/(.+[0-9]+)(.+)/", $word,-1, PREG_SPLIT_DELIM_CAPTURE | PREG_SPLIT_NO_EMPTY); print_r($keywords);
Output:-https://eval.in/1006421
Explanation:-
/(.+[0-9]+)(.+)/ 1st Capturing Group (.+[0-9]+) .+ matches any character (except for line terminators) + Quantifier — Matches between one and unlimited times, as many times as possible, giving back as needed (greedy) Match a single character present in the list below [0-9]+ + Quantifier — Matches between one and unlimited times, as many times as possible, giving back as needed (greedy) 0-9 a single character in the range between 0 (index 48) and 9 (index 57) (case sensitive) 2nd Capturing Group (.+) .+ matches any character (except for line terminators) + Quantifier — Matches between one and unlimited times, as many times as possible, giving back as needed (greedy)