Extracting a string

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
visionmaster
Forum Contributor
Posts: 139
Joined: Wed Jul 14, 2004 4:06 am

Extracting a string

Post by visionmaster »

Hello,

I guess my question is simple but at the moment I don't know how to do it. :-(

I would like to do following: Parse a string (one webpage) for 72393. If I find 72393 in the page I want to "pull out" a string 50 characters
ahead of 72393 (including 72393). How do I do that?

How about 50 characters ahead of 72393 and 50 characters behind 72393?

For example:
company Name<br>
Street 5<br>
72393 Example-City<br>

The extracted string should then be changed to a array of string (using explode).

Thanks!
User avatar
Buddha443556
Forum Regular
Posts: 873
Joined: Fri Mar 19, 2004 1:51 pm

Post by Buddha443556 »

Didn't test it but ....

Code: Select all

preg_match_all("/([^<]*)<br>([^<]*)<br>72393([^<]*)<br>/", $data, $matches);
$matches will contain:
Orders results so that $matches[0] is an array of full pattern matches, $matches[1] is an array of strings matched by the first parenthesized subpattern, and so on.
User avatar
JAM
DevNet Resident
Posts: 2101
Joined: Fri Aug 08, 2003 6:53 pm
Location: Sweden
Contact:

Post by JAM »

I'd prefer using strstr (to find) and substr (to choose lenght) and (optionally) strlen.

Code: Select all

$string = '
Testing test<br>
Testing test<br>
Testing test<br>
Testing test<br>
company Name<br>
Street 5<br>
72393 Example-City<br>1234567890 1234567890 1234567890 1234567890 1234567890 1234567890 1234567890 FOOBAR';

$tofind = '72393';
$found = substr(strstr(strip_tags($string), $tofind), strlen($tofind), 50); // strip_tags, find needle, go from there.
echo $found .' : '. strlen($found); // example output
Result:

Code: Select all

Example-City 1234567890 1234567890 1234567890 12 : 50
visionmaster
Forum Contributor
Posts: 139
Joined: Wed Jul 14, 2004 4:06 am

Post by visionmaster »

Code: Select all

...
$tofind = '72393';
$found = substr(strstr(strip_tags($string), $tofind), strlen($tofind), 50); // strip_tags, find needle, go from there.
echo $found .' : '. strlen($found); // example output&#1111;/php]

Result:&#1111;code]Example-City 1234567890 1234567890 1234567890 12 : 50
That looks good, but what if I wanted
50 characters before 72393
or
50 characters before and after 72393.
=>All I just want is a "range" or "intervall".


Thanks
Post Reply