I am modifying a WordPress theme and I want to show a limited number of characters displayed in a story on the homepage and include a link to the rest of the story. This should be done automatically without the author having to specify the point where the break occurs. However, I want to allow the use of html tags, but I don’t want to split the story until the tags are closed.
The code that I am working with included the function strip_tags
to make sure that the character break did not occur in the middle of an html tag. However, the content authors wanted to be able to include some tags, and over time the previous webmaster modified the theme to allow some tags such as <p>
,<i>
,etc. However, now I am working on the site and the content authors would really like to be able to include things like links and images. I tried commenting out the strip_tags
command but now understand why it was included because splitting the text at an arbitrary point can be problematic if it is in the middle of a tag or if the tag is not closed properly.
I’m trying to figure out if php has a provision for making sure tags are closed so I can do that before splitting the text. Or maybe some other alternative. A snippet from code I am working with is shown below.
$content = get_the_content('', $stripteaser, $more_file);
$content = apply_filters('the_content', $content);
$content = str_replace(']]>', ']]>', $content);
//Commenting out following line causes problems
//$content = strip_tags($content, '<p><br><b><i><strong><em>');
if ((strlen($content)>$max_char) && ($espacio = strpos($content, " ", $max_char ))) {
$content = substr($content, 0, $espacio);
$content = $content;
echo "<p>";
echo $content;
echo "...";
echo " <a rel='nofollow' href='";
the_permalink();
echo "'>".$more_link_text."</a>";
echo "</p>";
}
If you don’t want to use the_excerpt(), you can read more about the More Tag to do everything you’re describing without the use of filters or regular expressions.
If you’re REALLY curious about using a regular expression to detect a More Tag, however, then this would be the string you need: