- preg_match: documentation ( source)
- str_replace: documentation ( source)
- strtolower: documentation ( source)
<?php
function convertHashtags($str) {
$regex = '/@([a-zA-Z0-9]+[\sa-zA-Z0-9]*)/';
if(preg_match($regex,$str,$matches) === 1){
list($username,$name) = [$str , strtolower(str_replace(' ','',$matches[1]))];
return "<a href='profile?id=$name'>$username</a>";
}
throw new Exception('Unable to find username in the given string');
}
$string = 'I am @Marie Lee, nice to meet you!';
$string = convertHashtags($string);
echo $string;