dousongxuan7507 2015-04-18 21:48
浏览 24
已采纳

获得wordpress标题的一部分

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.

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 ?

  • 写回答

1条回答 默认 最新

  • dtest84004 2015-04-18 22:08
    关注
    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;
      }
      
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 三菱伺服电机按启动按钮有使能但不动作
  • ¥20 为什么我写出来的绘图程序是这样的,有没有lao哥改一下
  • ¥15 js,页面2返回页面1时定位进入的设备
  • ¥200 关于#c++#的问题,请各位专家解答!网站的邀请码
  • ¥50 导入文件到网吧的电脑并且在重启之后不会被恢复
  • ¥15 (希望可以解决问题)ma和mb文件无法正常打开,打开后是空白,但是有正常内存占用,但可以在打开Maya应用程序后打开场景ma和mb格式。
  • ¥20 ML307A在使用AT命令连接EMQX平台的MQTT时被拒绝
  • ¥20 腾讯企业邮箱邮件可以恢复么
  • ¥15 有人知道怎么将自己的迁移策略布到edgecloudsim上使用吗?
  • ¥15 错误 LNK2001 无法解析的外部符号