简体   繁体   中英

PHP RegEx add space

I have the following string:

John 1:9

and the following php code:

$parts = preg_split('/[^a-z]/i', $a,2);
var_dump($parts);

It returns the following result (as i expect)

array (size=2)
  0 => string 'John' (length=4)
  1 => string '1:9' (length=3)

However, i might want the book "1 John 1:9" and it doesn't work to detect "1 John". How do i need to change the regex code to accept numbers 1-4 and a space before the book name?

How about:

preg_match('/^((?:\d{1,4} )?\S+) (.+)$/', $string, $matches);

The book name (with optional number) is in $matches[1] and the rest in $matches[2]

Rather than just splitting then you'll need to write a regex to match each part.

You could use something like:

/^((?:[1-4] )?[a-z]+) ([\d:]*)$/

Then you'd use preg_match as follows:

preg_match('/^((?:[1-4] )?[a-z]+) ([\d:]*)$/', $string, $parts);

I think the easiest way is to check if the first result is numeric and if so join the first two keys.

$parts = preg_split('/[^a-z]/i', $a);
if (is_numeric($parts[0])) {
    $parts[0] = array_shift($parts) . ' ' . $parts[0];
}
var_dump($parts);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM