1

I have a titles such as The Oak Tree or The Pine

I set up $stylename = explode("The", $row->title);

This should explode the phrase into

$stylename[0] = 'The'; $stylename[1] = 'Oak Tree';

But instead $stylename[0] is empty.

How can I alter the above code to export what I require?

Thanks

2
  • 2
    You might want to split on whitespace instead. Commented Mar 3, 2014 at 9:02
  • 3
    Explode eliminates the item used as delimiter that's why The is not present. Commented Mar 3, 2014 at 9:03

5 Answers 5

3

Explode splits at the string you give it, so you have "" (nothing) then "The" (which was what it split at) then (the rest of it), more simply "abc" when you explode with b yields the two strings "a" and "c".

Use preg_split with a trivial regex instead, or artificially add the "the" back in, Regex is better as you can make it case insensitive, which you probably want ("the" in titles should have a lower case "t")

Sign up to request clarification or add additional context in comments.

Comments

1

Use preg_split:

// split on the spaces which has `The` in front of it.
$stylename = preg_split('/(?<=The)\s+/', $row->title);

Comments

0

explode(" ", $row->title, 1) should do it the way you want.

1 is the limit of how many times the given string should be splitted.

See http://php.net/explode

Comments

0

Try

$stylename = explode(" ", "The Oak tree");
$result[0] = $stylename[0];
unset($stylename[0]);
$result[1] = implode(" ",$stylename);
unset($stylename);

see demo here

Comments

0

do this

$stylename = explode(" ", trim($row->title),1);

This should work

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.