preg_replace在发布表单时添加#如果丢失

So I'm somewhat familiar with preg_replace and I'm using it throughout my site to do a number of things. However, I can't seem to identify a solution to achieve this one goal, as I'm trying to perform this check at the time of posting the data.

I have a form that has a text field for only the purpose of a hashtag and text to be entered (#example). I basically just need to check to see if the user entered a hashtag for the first character and if not, then add it when the form is posted. If the user entered a hashtag then nothing needs to be changed. This is my code that I'm using right now and it works as desired, but I need to ensure a hashtag is being entered first.

$data = preg_replace('#[^\#a-z0-9]#i', '', $_POST['data']);

You described exactly what you need to do! Just check if the first character is a pound symbol, if not, add it. You wouldn't use preg_replace in this case.

$data = ...;
$data = ($data{0} == "#" ? "":"#") . $data;