0

According to this post remove everything after first comma from string in php

I need customize this line in Wordpress:

<div class="text-center font-weight-bold" style="font-size: 16px; line-height: 16px; text-decoration: underline;">
    <?php 
        echo rtrim( wp_trim_words( get_the_title(), 2, '' ), ',' ); 
    ?>
</div>

It works good, but some product titles need to be longer than two words, so i need all words before comma character.

Juraj
  • 458
  • 8
  • 18

2 Answers2

2

You could also use preg_replace

$f = "Hello there, im a post title, and some stuff";

echo preg_replace("/,.+/", "", $f); // Hello there
Kyrre
  • 670
  • 1
  • 5
  • 19
  • Thank you too, but regular expression is not unnecessary? – Juraj Nov 04 '19 at 12:44
  • 1
    It might be more costly than ```explode``` in this case, but its applications are way broader. Regex is a powerful tool, and certainly one you should endeavor to learn. – Kyrre Nov 04 '19 at 12:47
  • 2
    An important part about learning any tool is when it's appropriate. Regex are as you say very powerful and can do a lot, but in this example the need is so basic as for it to be not needed. – Nigel Ren Nov 04 '19 at 13:02
  • 1
    @Kyrre I agree with you, but NigelRen is right also. You should know when to use it. But knowing regex has proved useful countless of times. I have upvoted your answer, as it works and someone might find it useful for their particular use-case. – Martin Dimitrov Nov 04 '19 at 13:10
1

Try doing it with explode()

<div class="text-center font-weight-bold" style="font-size: 16px; line-height: 16px; text-decoration: underline;">
    <?php 
        echo explode(',', get_the_title())[0]; 
    ?>
</div>
Martin Dimitrov
  • 1,304
  • 1
  • 11
  • 25