user3259342 user3259342 -4 years ago 105
PHP Question

How would I select the first word only on this string

I have a bit of code that is currently working and returning a location variable.
How do I make it so it only takes the first word of a variable?
Currently it is returning for example "Inverness, Highland"
I want it to return "Inverness" Only.

<?php
echo apply_filters(
"adverts_tpl_single_location",
esc_html( get_post_meta( $post_id, "adverts_location", true ) ),
$post_id )
?>

Answer Source

You could use explode():

$all_locations = apply_filters( 
    "adverts_tpl_single_location", 
    esc_html( get_post_meta( $post_id, "adverts_location", true ) ), 
    $post_id );
$locations = explode(',', $all_locations); // since the list is comma separated
echo $locations[0]; // should be 'Inverness' 
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download