Kyle Hudson
Kyle Hudson

Reputation: 898

matching a string using php preg_match

I am stuck.

I am trying to see 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

Upvotes: 0

Views: 835

Answers (4)

Daniel Vandersluis
Daniel Vandersluis

Reputation: 94123

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.

Upvotes: 0

bcosca
bcosca

Reputation: 17555

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

Use:

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

Upvotes: 1

mishu
mishu

Reputation: 5397

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.

Upvotes: 0

slobodan
slobodan

Reputation: 209

try

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

Upvotes: 0

Related Questions