Skip to content
PHP Logo

How does the substr function help in truncating the text between <a> and </a> tags in the PHP code?

To truncate text between <a> and </a> tags in PHP, we can use the substr function to extract the desired portion of the text. We can first find the position of the opening and closing <a> tags using strpos, then use substr to extract the text between these positions.

php
$text = "<a>This is the text between the tags</a>";
$start_tag = "<a>";
$end_tag = "</a>";

$start_pos = strpos($text, $start_tag) + strlen($start_tag);
$end_pos = strpos($text, $end_tag);

$truncated_text = substr($text, $start_pos, $end_pos - $start_pos);

echo $truncated_text;