user1282355
user1282355

Reputation: 143

How do I split a sentence by a specific word with php?

How can I split a sentence or string into two different parts?

$string = "First Name Last Name on 4/30/13";
$string = "First Name on 4/28/13";
$string = "First Name Last Name";

how do I extract the name, and the date into two different variables? The string changes. It sometimes has on Date, and sometimes doesn't.

Upvotes: 1

Views: 505

Answers (3)

Get Off My Lawn
Get Off My Lawn

Reputation: 36311

You can do this, here is an example of each one

<?php
$string = "First Name Last Name on 4/30/13";
print_r(explode(" on ", $string));

$string = "First Name on 4/28/13";
print_r(explode(" on ", $string));

$string = "First Name Last Name";
print_r(explode(" on ", $string));

And here is the output:

Array
(
    [0] => First Name Last Name 
    [1] => 4/30/13
)
Array
(
    [0] => First Name 
    [1] => 4/28/13
)
Array
(
    [0] => First Name Last Name
)

Upvotes: 0

Javier Parra
Javier Parra

Reputation: 2080

Seems to me that you need to use regular expressions.

Check the documentation for preg_match and Regular Expressions.

Upvotes: 0

Jon
Jon

Reputation: 437376

The simplest would be to use explode, perhaps like this:

 list($name, $date) = array_pad(explode(' on ', $string), 2, null);

This will assign the name to $name and the date to $date; if there is no date, $date will be null.

Be mindful of the fact that explode is quite dumb and will happily break up the name if it contains the string ' on '. In this case this is highly unlikely because I have included the surrounding spaces in the string, but the more naive explode on 'on' would easily backfire with a name like "Marion Jones".

For more advanced matching you would have to move up to regular expressions and preg_match.

Upvotes: 1

Related Questions