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..

  • 写回答

2条回答 默认 最新

  • duanou3868 2014-03-24 13:54
    关注

    For common (not just c-) case:

    $slug="my-string-content-123";
    if(preg_match('/([^0-9]+)-([0-9]+)$/', $slug, $matches))
    {
       //prefix is in $matches[1];
       //the number is in $matches[2];
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥30 这是哪个作者做的宝宝起名网站
  • ¥60 版本过低apk如何修改可以兼容新的安卓系统
  • ¥25 由IPR导致的DRIVER_POWER_STATE_FAILURE蓝屏
  • ¥50 有数据,怎么建立模型求影响全要素生产率的因素
  • ¥50 有数据,怎么用matlab求全要素生产率
  • ¥15 TI的insta-spin例程
  • ¥15 完成下列问题完成下列问题
  • ¥15 C#算法问题, 不知道怎么处理这个数据的转换
  • ¥15 YoloV5 第三方库的版本对照问题
  • ¥15 请完成下列相关问题!