1024programmer Java Using preg_split to go from ‘hihowareyou’ to [hi,howareyou]

Using preg_split to go from ‘hihowareyou’ to [hi,howareyou]

I want to split a string into two parts, the string is almost free text, for example:

I want to split a string into two parts, the string is almost free text, for example:

$string = 'hi how are you';
 

and i want the split to look like this:

I want the split to look like this:

array(
     [0] => hi
     [1] => how are you
 )
 

I tried using this regex: /(\S*)\s*(\.*)/ but even when the array returned is the correct size, the values ​​comes empty.

I tried using this regex: /(\S*)\s*(\.*)/ but even though the returned array is the correct size, The value is also empty.

What should be the pattern necessary to make this works?

What should be the pattern to make this effective?

2 solutions

#1


What are the requirements? Your example seems pretty arbitrary. If all you want is to split on the first space and leave the rest of the string alone, this would do it, using explode:

What are the requirements? Your example seems very arbitrary. If all you want is to split on the first space and leave the rest of the string, then use explode:

$pieces = explode(' ', 'hi how are you', 2);
 

Which basically says “split on spaces and limit the resulting array to 2 elements”

This basically says “split on spaces and limit the resulting array to 2 elements”

#2


You should not be escaping the “.” in the last group. You’re trying to match any character, not a literal period.

You should not escape the “.” in the last group. You’re trying to match any character, not the literal period.

Corrected: /(\S*)\s*(.*)/

This article is from the internet and does not represent1024programmerPosition, please indicate the source when reprinting:https://www.1024programmer.com/756938

author: admin

Previous article
Next article

Leave a Reply

Your email address will not be published. Required fields are marked *

Contact Us

Contact us

181-3619-1160

Online consultation: QQ交谈

E-mail: [email protected]

Working hours: Monday to Friday, 9:00-17:30, holidays off

Follow wechat
Scan wechat and follow us

Scan wechat and follow us

Follow Weibo
Back to top
首页
微信
电话
搜索