Get part of the wordpress title

My wp post titles currently look like this:

Hamlet (by William Shakespeare)
Romeo and Juliet (by William Shakespeare)
A Midsummer Night’s Dream (by William Shakespeare)
etc.

Read More

I am using this code:

<?php
    echo strtolower(str_replace(' ', '', get_the_title()));
?>

to get each title but I only need the first part of the title without the text that is in parenthesis.

i.e

Hamlet
Romeo and Juliet
A Midsummer Night’s Dream
etc.

How can I modify the code so that it will get only the first part of the title without what is in between the parenthesis ?

Related posts

Leave a Reply

1 comment

    1. Loop over each character in the string, adding them to an auxiliary variable. If you hit a ( then stop.

      $string = 'Romeo and Juliet (by William Shakespeare)';
      $result = '';
      for ($i = 0, $l = strlen($string) - 1; $i < $l; $i++) {
          if ($string[$i] === '(') {
              break;
          }
          $result .= $string[$i];
      }
      $string = trim($result);
      
    2. Find the first parenthesis and then cut out the text before that.

      $string = 'Romeo and Juliet (by William Shakespeare)';
      $first  = strpos($string, '(');
      if ($first !== false) {
          $string = substr($string, 0, $first);
      }
      $string = trim($string);
      
    3. Split the string in half by the first (. Then use the first part.

      $string = 'Romeo and Juliet (by William Shakespeare)';
      $parts  = explode('(', $string, 2);
      $string = trim(array_shift($parts));
      
    4. Use a regular expression:

      $string = 'Romeo and Juliet (by William Shakespeare)';
      preg_match('/[^(]+/', $string, $result);
      $string = trim(array_shift($result));
      
    5. And a bonus one! If you are going to do this more than once then a function like this should do the trick. You should probably rename it.

      function awesomeness($string) {
          $paren = strpos($string, '(');
          if ($paren !== false) {
              $string = substr($string, 0, $paren);
              $string = trim($string);
          }
          return $string;
      }