PHP: How to find the beginning and end of a substring in a string?
Asked Answered
B

3

0

This is the content of one mysql table field:

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

Now, I want to read the remarks and store them in a variable. Remarks(1), Remarks(2), etc. are fixed. 'this is remark1', etc. come from form input fields, so they are flexible.

Basically what I need is: Read everything between 'Remarks(1):' and '--------' and save it in a variable.

Thanks for your help.

Batt answered 14/9, 2010 at 4:38 Comment(2)
Do these remarks always span a single line?Snout
Why do you need to do this? The data should probably be stored in a proper table structure in the database.Aesthetic
S
1

You can use regex:

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

As seen on ideone.

The regex will put X in match group 1, Y in match group 2 (Remarks(X): Y)

Snout answered 14/9, 2010 at 4:45 Comment(2)
Great thanks, that works for me. But how do I save each remark in a separate variable?Batt
They will be in an array ($m[2]), so you could do list($remark1, $remark2, $remark3, $remark4) = $m[2]). But an array looks cleaner IMO (eg: $remarks = $m[2])Snout
D
0

This would be a job for regular expressions, which allow you to match on exactly the kinds of rules your requirements express. Here is a tutorial for you.

Desimone answered 14/9, 2010 at 4:42 Comment(0)
C
0

Use preg function for this or otherwise you can explode and implode function to get correct result. Don't Use Substring it may not provide correction.

Example of Implode and Explode Function for your query string :

    $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>";

Your Answer :

First String - Remarks(4)

Second String - this is remark4
Culm answered 14/9, 2010 at 5:2 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.