简体   繁体   English

使用php preg_match匹配字符串

[英]matching a string using php preg_match

I am stuck. 我被困住了。

I am trying to see if an textarea contains an #. 我正在尝试查看textarea是否包含#。

This is what I am trying but it doesnt work. 这是我正在尝试的方法,但是没有用。

Example: 例:

#firstname# - should trigger "processTaggedMessage"

whereas

firstname - should trigger "processNormalMessage"

The code (PHP): 代码(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 我敢肯定这很简单,但我看不到,我相信正则表达式是正确的:S

Thanks, 谢谢,

Kyle 凯尔

Get rid of the ^ and $ if you're trying to match several substrings delimited by # . 如果要匹配以#分隔的几个子字符串,请除去^$

Use: 采用:

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

PCRE regular expressions in PHP need to be delimited . PHP中的PCRE正则表达式需要定 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# . 这意味着除非整个字符串为#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. 顺便说一句,由于您在注释中提到在目标字符串中搜索的内容多次出现,因此您可能希望使用preg_match_all而不是preg_match以便收集所有匹配项。

尝试

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

try 尝试

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

and you could also take a look here: 您也可以在这里看看:

http://php.net/preg_match 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. 如果只想检查一个字符串是否包含在另一个字符串中,请不要使用preg_match()。 Use strpos() or strstr() instead as they will be faster. 请改用strpos()或strstr(),因为它们会更快。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM