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;
      }
      
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥20 java-OJ-健康体检
  • ¥15 rs485的上拉下拉,不会对a-b<-200mv有影响吗,就是接受时,对判断逻辑0有影响吗
  • ¥15 使用phpstudy在云服务器上搭建个人网站
  • ¥15 应该如何判断含间隙的曲柄摇杆机构,轴与轴承是否发生了碰撞?
  • ¥15 vue3+express部署到nginx
  • ¥20 搭建pt1000三线制高精度测温电路
  • ¥15 使用Jdk8自带的算法,和Jdk11自带的加密结果会一样吗,不一样的话有什么解决方案,Jdk不能升级的情况
  • ¥15 画两个图 python或R
  • ¥15 在线请求openmv与pixhawk 实现实时目标跟踪的具体通讯方法
  • ¥15 八路抢答器设计出现故障