duangan7834
2014-03-24 13:50
浏览 53
已采纳

在php中用正则表达式查找字符串

I am new to regex and therefore i gone through php manual for regex and tried the below:

i have a string like this:

c-1

c-10

c-100 and so on upto c-unlimited

now i want to confirm that the string coming is a valid string which starts with c- and after c- it only contains numbers..

to get this work i have used preg_match

$slug='c-12';

if(preg_match("/\[c-(.*?)]/",$slug,$result)){ echo "TRUE";}
else{ echo "FALSE"; }

also this:

$pattern = '/^c-/';
if(preg_match($pattern, substr($slug,2), $matches, PREG_OFFSET_CAPTURE){ echo "TRUE";}
else{ echo "FALSE"; }

and also this:

$pattern = '/^c-/';
if(preg_match($pattern, $slug, $matches, PREG_OFFSET_CAPTURE, 3){ echo "TRUE";}
else{ echo "FALSE"; }

and one more thing i also wanted to to validate the string from end. like below:

 $slug="my-string-content-123";

here i wanted to validate that the string contains the number at end after -

example 123

but i am not able to get it work... and i am sorry for my bad english..

any help or suggesstion would be a great help.. thanks in advance..

图片转代码服务由CSDN问答提供 功能建议

我是regex的新手,因此我通过php手册进行了正则表达式并尝试了以下内容: \ n

我有一个这样的字符串:

c-1

c- 10

c-100 ,依此类推至 c-unlimited

现在我想确认字符串是一个有效的字符串,以 c - 开头,在 c - 之后它只包含数字.. \ n

为了完成这项工作,我使用了 preg_match

  $ slug ='c-12'; 
 
if(preg_match(“  / \ [c  - (。*?)] /“,$ slug,$ result)){echo”TRUE“;} 
else {echo”FALSE“;  } 
   
 
 

也是这样的:

  $ pattern ='/ ^ c  -  /'; 
if(preg_match  ($ pattern,substr($ slug,2),$ matches,PREG_OFFSET_CAPTURE){echo“TRUE”;} 
else {echo“FALSE”;} 
   
 
 

还有这个:

  $ pattern ='/ ^ c  -  /'; 
if(preg_match($ pattern,$ slug,$ matches,PREG_OFFSET_CAPTURE,3){echo“  TRUE“;} 
else {echo”FALSE“;} 
   
 
 

还有一件事我还想从结尾验证字符串。如下所示:

  $ slug =“my-string-content-123”; 
   
 
 

这里我想验证字符串 包含 -

示例 123

之后的数字,但我无法 让它工作......我很抱歉我的英语不好..

任何帮助或建议都会有很大的帮助..提前感谢..

  • 写回答
  • 好问题 提建议
  • 追加酬金
  • 关注问题
  • 邀请回答

2条回答 默认 最新

相关推荐 更多相似问题