Reputation: 898
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
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
Reputation: 17555
Get rid of the ^
and $
if you're trying to match several substrings delimited by #
.
Use:
preg_match('/#.*?#/s', $msg)
Upvotes: 1
Reputation: 5397
try
if (preg_match('/^(.*)#(.*)$/', $msg))
and you could also take a look here:
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