开发者

Script that recognizes first sentence, put it inside a heading and the rest inside a paragraph

开发者 https://www.devze.com 2023-02-17 01:44 出处:网络
Hey there, I have this code, i take a wordpress post content, put it inside a variable and than match the first sentence, put it inside a h2 heading and the rest inside a paragraph.

Hey there, I have this code, i take a wordpress post content, put it inside a variable and than match the first sentence, put it inside a h2 heading and the rest inside a paragraph.

1.The problem is this... my script recognizes only . or ! or ? at the end of the first sentance. Can i make it recognize "..." suspension points?

2.If in my wordpress post i have a text like this:

The first sentance! followed by some text

than i hit enter

continue with more text

My script shows only "The first sentance! followed by some text" and nothing after the enter that i hit. Why? and ideeas?

Here is the code:

ob_start();
the_content();
$old_content = ob_get_clean(); // I put wordpress inside a variable
$content = strip_tags($old_content); // I use strip tags

     preg_match('/(.*?[?.!])(.*)/', $content, $match); 
     $first_sentence = $match[1]; 
     $the_rest = $match[2];

     if ( $first_sentence != '' && $the_rest != '' ):
             echo '<h2>'.$first_sentence.'</h2>';
             echo '<p>'.$the_rest.'</p>';
     else:开发者_C百科
     echo '<h2>About me:</h2>';
     endif;


 preg_match('/(.*?[?\.!]{1,3})(.*)/', $content, $match); 

Should do it without complicating it too much. It will recognize ..., !!!, ??? that looks ok, but keep in mind that .!? will also fit. I'm unfortunately unable to test anything more complicated at the moment.

Update

Regarding the second question. It's because regular expression ends at line break. You can turn on multiline mode with '/(.*?[?\.!]{1,3})(.*)/m' if I'm not mistaken. But I would suggest changing the code to:

 preg_match('/(.*?[?\.!]{1,3})/', $content, $match);
 $first_sentence = $match[1]; 
 $the_rest = substr($content, strlen($first_sentence));

as it will have greater performance


Can't you just take everything up to the first newline?

Something like:

$firstnewline = strpos($text, "\n");
$header = substr($text, 0, $firstnewline);
$therest = substr($text, $firstnewline + 1);

If you want, you can do further processing using strip_tags(), a regexp, or a simple str_replace().

0

精彩评论

暂无评论...
验证码 换一张
取 消