How to Make a Hashtag and Mention System in PHP without regex

hashtag

I am not a big fan of regex in PHP.
The following way is how I convert text hashtags to hyperlinks using only string functions.

  1. function hashtagtolink($str) { 
  2.     $hash_pos = strlen($str); 
  3.     while (($hash_pos = strrpos(rtrim(substr($str, 0, $hash_pos), '#'), '#')) !== false) { 
  4.         if ($hash_pos /* > 0 */ && strspn($str[$hash_pos - 1], '&;')) { 
  5.             continue; 
  6.         } 
  7.         $hash_str = substr($str, $hash_pos + 1) . ' '; 
  8.         if (($tag_len = strpos($hash_str, ltrim($hash_str, '-0..9A..Za..z_'))) > 0) { 
  9.             $tag_str = substr($hash_str, 0, $tag_len); 
  10.             $str     = substr_replace($str, '<a href="/tag/' . $tag_str . '">#' . $tag_str . '</a>', $hash_pos, $tag_len + 1); 
  11.         } 
  12.     } 
  13.     return $str; 
  14. } 

To satisfy regex users, I have posted the regex version on https://anggit.com/archive/201903/post/0314424100/cara-membuat-sistem-hashtag-dan-mention-di-php-dengan-regex.html

"Ingenious ideas are simple. Ingenious software is simple. Simplicity is the heart of the Unix philosophy. The more code lines you have removed, the more progress you have made. As the number of lines of code in your software shrinks, the more skilled you have become and the less your software sucks."

* Keep checking this post for the latest revisions.
#PHP#string ###PHP #string