get first word of an ACF field

I’m using ACF on my wordpress website, and to create a div id I would like to get the first word from a AC Field.
For example, I have a field called “Titre”, and the text inside is for example Made Under Authority.
I need to create a like this :

<div id="<?php the_sub_field('titre'); ?"> 

I’m using Anchors on my website that’s why I need to do this.
It works fine, with one word fields, but in this case my div will be

Read More
<div id="Made Under Authority">

so it won’t works with the blank spaces…

what I need is to only get the first word from my text field to generate my div name, and in lowercase.
I know how do it with a normal text, but not with ACF… Anybody can help me ?

here is my PHP code

<?php if(get_field('album')): ?>
<?php while(has_sub_field('album')): ?>
<div id="<?php the_sub_field('titre'); ?>">
</div>
<?php endwhile; ?>  
<?php endif; ?>

thanks a lot for your help

Related posts

Leave a Reply

1 comment

  1. First of all use get_sub_field instead of the_sub_field. “the” will echo string automatically, “get” will return it.

    So your code could look like this:

    <div id="<?php echo strtolower(explode(' ', get_sub_field('titre'), 2)[0]) ?>">

    But as far as I remember this will for PHP 5.4 (because explode(...)[0]) thing.

    EDIT

    Without explode but with strtok:

    <div id="<?php echo strtolower(strtok(get_sub_field('titre'), ' ')) ?>">