mb_substr cutting off words in post excerpt?

2019-09-05 07:16发布

问题:

This is the code I am using to show html formatting on my wordpress post excerpts:

 function get_excerpt($post, $ln){
        if (!empty($post->post_excerpt)) {
            if (strlen($post->post_excerpt) > $ln) {
                echo mb_substr(($post->post_excerpt), 0, $ln);
            } 
        } else {
            if (strlen($post->post_content) > $ln) {
                  echo mb_substr(($post->post_content), 0, $ln);
            } 
        }

    }

How can I edit the mb_substr so that the excerpt will end at a period? For instance, an excerpt will end like this "she has a lovable and innocent charm tha" instead of "she has a lovable and innocent charm that keeps people caring about her." I want the excerpt to finish the sentence and end in a period instead of only stopping at the character limit, which is set at 800. In the code $ln is set to 800.

UPDATE:

This is the code I ended up using. Words are still cut off in the excerpt but I added a Read More link to the end with dots.

 function get_excerpt($post, $ln){
    if (!empty($post->post_excerpt)) {
        if (strlen($post->post_excerpt) > $ln) {
            echo mb_substr(($post->post_excerpt), 0, $ln) . '...'; ?> <a href="<?php echo get_permalink( $post -> ID )?>">[Read More]</a>
 <?php } 
    } else {
        if (strlen($post->post_content) > $ln) {
              echo mb_substr(($post->post_content), 0, $ln) . '...';?> <a href="<?php echo get_permalink( $post -> ID )?>">[Read More]</a>
 <?php } 
    }

}

回答1:

If you can guarantee that there will be a "." in your text then you can just do this:

echo strtok("Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nam sit amet egestas lacus. Maecenas posuere dolor vitae ultrices viverra.",".");

This will output: "Lorem ipsum dolor sit amet, consectetur adipiscing elit"

strtok manual page