Click to See Complete Forum and Search --> : Is there a predefined function for this?
amahmood
07-14-2005, 06:36 PM
I wonder if there is a predefined function to extract part of a string given the beginning and the end of the piece we want. for example from the following string:
$myString = "onetwo threefourfive sixseveneight";
I want the piece between "two" and "five" ie: " three four".
at the moment I extract the part by looping throught the string array.
Any advise?
ShrineDesigns
07-14-2005, 07:42 PM
you could you preg_match() or preg_match_all()
example<?php
function get_piece($str, $start, $end)
{
if(preg_match("/" . $start . "(.*)" . $end . "/", $str, $m))
{
return $m[1];
}
}
$str = "onetwo threefourfive sixseveneight";
echo get_piece($str, 'two', 'five'); // should output: ' threefour'
?>
amahmood
07-14-2005, 08:04 PM
Thanks ShrineDesigns
That works just fine.
amahmood
07-14-2005, 09:09 PM
And how about some chracters such as "."?
ShrineDesigns
07-15-2005, 04:40 AM
try this<?php
function get_piece($str, $start, $end)
{
// escapes any regex characters
$start = preg_quote($start);
$end = preg_quote($end);
if(preg_match("/" . $start . "(.*)" . $end . "/", $str, $m))
{
return $m[1];
}
}
$str = "onetwo threefourfive sixseveneight";
echo get_piece($str, 'two', 'five'); // should output: ' threefour'
?>