【问题标题】:PHP: How to find the beginning and end of a substring in a string?PHP:如何在字符串中找到子字符串的开头和结尾?
【发布时间】:2010-09-14 04:38:21
【问题描述】:

这是一个mysql表字段的内容:

Flash LEDs: 0.5W
LED lamps: 5mm
Low Powers: 0.06W, 0.2W
Remarks(1): this is remark1
----------
Accessories: Light Engine
Lifestyle Lights: Ambion, Crane Fun
Office Lights: OL-Deluxe Series
Street Lights: Dolphin
Retrofits: SL-10A, SL-60A
Remarks(2): this is remark2
----------
Infrared Receiver Module: High Data Rate Short Burst
Optical Sensors: Ambient Light Sensor, Proximity Sensor, RGB Color Sensor
Photo Coupler: Transistor
Remarks(3): this is remark3
----------
Display: Dot Matrix
Remarks(4): this is remark4

现在,我想阅读备注并将它们存储在一个变量中。备注(1)、备注(2)等是固定的。 'this is remark1'等来自表单输入字段,因此很灵活。

基本上我需要的是:读取 'Remarks(1):' 和 '--------' 之间的所有内容并将其保存在变量中。

感谢您的帮助。

【问题讨论】:

  • 这些注释总是跨越一行吗?
  • 为什么需要这样做?数据可能应该存储在数据库中适当的表结构中。

标签: php substr strstr


【解决方案1】:

你可以使用正则表达式:

preg_match_all("~Remarks\(([^)]+)\):([^\n]+)~", $str, $m);

如在ideone 上看到的那样。

正则表达式会将 X 放在匹配组 1 中,Y 放在匹配组 2 中(备注(X):Y)

【讨论】:

  • 非常感谢,这对我有用。但是如何将每条评论保存在单独的变量中?
  • 它们将在一个数组中($m[2]),所以你可以使用list($remark1, $remark2, $remark3, $remark4) = $m[2])。但是数组看起来更干净 IMO(例如:$remarks = $m[2]
【解决方案2】:

这将是正则表达式的工作,它允许您准确匹配您的需求表达的规则类型。 Here是给你的教程。

【讨论】:

    【解决方案3】:

    为此使用preg 函数,否则您可以分解和内爆函数以获得正确的结果。不要使用子字符串,它可能无法提供更正。

    查询字符串的 Implode 和 Explode 函数示例:

        $sdr = "Remarks(4): this is remark4";
    
        $sdr1 = explode(":",$sdr);
        $frst = $sdr1[0];
    
        $sdr2 = array_shift($sdr1);
    
        $secnd = implode(" ", $sdr1);
    
        echo "First String - ".$frst;
        echo "<br>";
        echo "Second String - ".$secnd;
        echo "<br>";
    

    你的答案:

    First String - Remarks(4)
    
    Second String - this is remark4
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多