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条)

报告相同问题?

悬赏问题

  • ¥15 mmocr的训练错误,结果全为0
  • ¥15 python的qt5界面
  • ¥15 无线电能传输系统MATLAB仿真问题
  • ¥50 如何用脚本实现输入法的热键设置
  • ¥20 我想使用一些网络协议或者部分协议也行,主要想实现类似于traceroute的一定步长内的路由拓扑功能
  • ¥30 深度学习,前后端连接
  • ¥15 孟德尔随机化结果不一致
  • ¥15 apm2.8飞控罗盘bad health,加速度计校准失败
  • ¥15 求解O-S方程的特征值问题给出边界层布拉休斯平行流的中性曲线
  • ¥15 谁有desed数据集呀