doutuan4361 2016-07-11 08:36
浏览 53
已采纳

preg_match检查字符串是否具有特定结构

How can I check with php with preg_match() if string has specific structure. For example string is:

options:blue;white;yellow;

I want to check if string starts with string followed by : followed by n-numbers of strings separated by ;

And something which is important - string may be in Cyrillic, not only latin letters

  • 写回答

1条回答 默认 最新

  • doutui839638 2016-07-11 08:56
    关注

    Assuming only the restrictions listed in your question are needed, this will validate the string:

    $number = 3;
    $regex = sprintf('/^[^:]+:(?:[^;]+;){%d}$/', $number);
    
    if (preg_match($regex, $string)) {
        echo "It matches!";
    } else {
        echo "It doesn't match!";
    }
    

    Here's an example of it in action, using php -a:

    php > $number = 3;
    php > $regex = sprintf('/^[^:]+:(?:[^;]+;){%d}$/', $number);
    
    php > if (preg_match($regex, 'options:blue;white;yellow;')) {
    php {     echo "It matches!";
    php { } else {
    php {     echo "It doesn't match!";
    php { }
    It matches!
    
    php > if (preg_match($regex, 'options:blue;white;yellow;green;')) {
    php {     echo "It matches!";
    php { } else {
    php {     echo "It doesn't match!";
    php { }
    It doesn't match!
    

    You can visualize this regex here. Let's break it down:

    /.../          Start and end of the pattern.
    ^              Start of the string.
    [^:]+          At least one character that is not a ':'.
    :              A literal ':'.
    (?:[^;]+;){N}  Exactly N occurrences of:
                       [^;]+  At least one character that is not a ';'.
                       ;      A literal ';'.
    $              End of the string.
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 公交车和无人机协同运输
  • ¥15 stm32代码移植没反应
  • ¥15 matlab基于pde算法图像修复,为什么只能对示例图像有效
  • ¥100 连续两帧图像高速减法
  • ¥15 如何绘制动力学系统的相图
  • ¥15 对接wps接口实现获取元数据
  • ¥20 给自己本科IT专业毕业的妹m找个实习工作
  • ¥15 用友U8:向一个无法连接的网络尝试了一个套接字操作,如何解决?
  • ¥30 我的代码按理说完成了模型的搭建、训练、验证测试等工作(标签-网络|关键词-变化检测)
  • ¥50 mac mini外接显示器 画质字体模糊