开发者

matching a string using php preg_match

I am stuck.

I am trying to se开发者_StackOverflow社区e if an textarea contains an #.

This is what I am trying but it doesnt work.

Example:

#firstname# - should trigger "processTaggedMessage"

whereas

firstname - should trigger "processNormalMessage"

The code (PHP):

(preg_match("^#(.*?)#$", $msg))
  ? $this->processTaggedMessage($fk_uid, $fk_cid, $sender, $msg, $num, $q)
  : $this->processNormalMessage($fk_uid, $fk_cid, $sender, $msg, $num, $q);

I am sure it is probs something simple but I cannot see it, I believe the regex is correct :S

Thanks,

Kyle


Get rid of the ^ and $ if you're trying to match several substrings delimited by #.

Use:

preg_match('/#.*?#/s', $msg)


try

preg_match('/^#(.*?)#$/', $msg)


try

if (preg_match('/^(.*)#(.*)$/', $msg))

and you could also take a look here:

http://php.net/preg_match

and you will find this:

Do not use preg_match() if you only want to check if one string is contained in another string. Use strpos() or strstr() instead as they will be faster.


PCRE regular expressions in PHP need to be delimited. You can try:

preg_match('/^#([^#]*)#$/', $msg)

Note that ^ and $ (as per your original pattern) specify that the pattern is anchored to the beginning and end of the string. This means your pattern will not match unless the entire string is #firstname#. If you want to search for #'s within a string, remove the anchors:

preg_match('/#([^#]*)#/', $msg)

Also, if you want to ensure that there is some text between the hashes, you should use + instead of * (/#([^#]+)#/). * means "zero or more repetitions", whereas + means "one or more repetitions".

By the way, since you mentioned in the comments that there are multiple occurrences of what you're searching for within your target string, you'll likely want to use preg_match_all instead of preg_match so that you can collect all the matches.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜