ngplayground
ngplayground

Reputation: 21627

Exploding by a word

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

Upvotes: 1

Views: 98

Answers (5)

Samy Massoud
Samy Massoud

Reputation: 4385

do this

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

This should work

Upvotes: 0

Nouphal.M
Nouphal.M

Reputation: 6344

Try

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

see demo here

Upvotes: 0

2cent
2cent

Reputation: 211

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

Upvotes: 0

xdazz
xdazz

Reputation: 160843

Use preg_split:

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

Upvotes: 1

Alec Teal
Alec Teal

Reputation: 5918

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

Upvotes: 3

Related Questions