代码之家  ›  专栏  ›  技术社区  ›  HandiworkNYC.com

获取字符串php中的第一个单词\u title WordPress

  •  2
  • HandiworkNYC.com  · 技术社区  · 15 年前

    有没有一种方法可以用PHP实现这一点?

    谢谢!

    更新:
    谢谢你的回答!我尝试了以下代码,但似乎不起作用。它仍然呼应完整的标题。有什么建议吗?

    <?php   
       $title = the_title();
       $names = explode(' ', $title);
       echo $names[0];
    ?>
    
    7 回复  |  直到 13 年前
        1
  •  10
  •   ahmet2106    15 年前

    这很简单:

    <?php
    $title = get_the_title(); // This must be!, because this is the return - the_title would be echo
    $title_array = explode(' ', $title);
    $first_word = $title_array[0];
    
    echo $first_word;
    ?>
    

    <?php
    $title = current(explode(' ', get_the_title()));
    
    echo $title;
    ?>
    

    希望这有帮助:)

        2
  •  5
  •   Galen    15 年前
    $first_word = current(explode(' ', $title  ));
    

    或者在模板文件中

    <?php echo current(explode(' ', $title  )) ?>
    

    按空格分解并获得结果数组中的第一个元素

        3
  •  2
  •   oezi    15 年前
    list($first_word) = explode(' ',$mystring);
    
        4
  •  0
  •   Sarfraz    15 年前

    $words = explode(' ', $the_title_here);
    echo $words[0];
    
        5
  •  0
  •   zombat    15 年前

    我想你可能在这里遇到了Wordpress的一些特质。 the_title() the_title() 是真的。

    //fetch the title string into a variable
    $title = the_title('','',true);
    

    strstr() :

    echo strstr($title," ",true);
    

    explode()

    $parts = explode(' ',$title);
    echo $parts[0];
    
        6
  •  0
  •   jerclarke    15 年前

    您应该使用WordPress的Post Meta系统定义一个名为subtitle的自定义Meta字段,然后在模板中调用该字段。这样你就可以一页一页地决定你想要的副标题是什么,而不是被锁定在文章标题和副标题之间的特定关系中。这可能不会让你的生活变得更复杂,而且会大大简化。

    您可以使用post编辑屏幕底部的“自定义字段”部分将post meta添加到页面或post。主题中的这些字段如下所示:

    <?php echo get_post_meta($post->ID, $meta_key, 1);?>
    

    <?php if ( $subtitle = get_post_meta($post->ID, $meta_key, 1) ) 
        echo "<h3>$subtitle</h3>";
    ?>
    

    More details on the codex.

        7
  •  0
  •   Krunal Shah    11 年前

    有一个字符串函数( strtok 代币 )基于某些分隔符。在本线程中,的第一个单词(定义为第一个空格字符之前的任何内容) Test me more 标志法 空格字符上的字符串。

    <?php
    $value = "Test me more";
    echo strtok($value, " "); // Test
    ?>
    

    有关更多详细信息和示例,请参见 strtok PHP manual page .