0

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?

3
  • What do you mean by the book name? What's your input and expected output? Commented Aug 4, 2014 at 11:20
  • "John" is a book name from the Bible, but it can also be "1 John" which is another book name. Also there is for example "1 Corinthians". A book name from the Bible with a number before. Commented Aug 4, 2014 at 11:21
  • preg_split('/([1-4])?\s?[a-zA-Z]', $a,2); should sort you out :) explaining: "It may have numbers from 1-to-4, it may have a space, and it has certainly letters from a-to-z, including capitals" Commented Aug 4, 2014 at 11:24

3 Answers 3

1

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);
Sign up to request clarification or add additional context in comments.

Comments

1

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]

Comments

0

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);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.