Page 1 of 1

Extracting data from a string without explode()?

Posted: Sat Dec 02, 2006 2:56 pm
by mattcooper
Hello all,

I have a CMS template that contains tags in the following format:

{-- dynamic_object [objectname] --}

The 'objectname' needs to be extracted and put into a database when a new page is created so that the CMS knows what objects to place on live pages. The number of these tags and 'objectname' will differ from template to template.

I've tried using explode() (first on '{-- dynamic_object [', and then on '] --}' in the resultant array, which I tried to convert back to a string) to extract 'objectname', but haven't achieved much apart from being slightly confused.

Does anyone know of an easier way to do this?

Thanks in advance,

Matt

Posted: Sat Dec 02, 2006 3:01 pm
by Burrito
if the name of your object and key will be the same length for all of them (not likely) you could use substr(). Otherwise, you'll probably need a regular expression.

edit: ahh yes...didn't think of using strpos() ... good call

Posted: Sat Dec 02, 2006 3:01 pm
by feyd
loop { 2 × strpos() + substr() }

Posted: Sat Dec 02, 2006 3:23 pm
by mattcooper
We're on the right lines. This function works in a limited way:

Code: Select all

function find_object($data_source, $start, $end, $start_position) {
		
		$start_pos = strpos($data_source, $start, $start_position);
		$middle_pos = $beginning_pos + strlen($beginning);
		$end_pos = strpos($data_source, $end, $start_pos + 1);
		$object = substr($data_source, $middle_pos, $end_pos - $middle_pos);
		return $object;
		
}
This

Code: Select all

$object = find_object($template_data, '{-- dynamic_object [', '] --}', 0);
returns the name of the first object in the template. If I put it into a loop that runs for the number of times set by count() of the array from explode(), I get the same object name x number of times.

How do I move the function on to the next object when I don't know where it is in the string?

Thanks for your time and help, and credit to the chap who posted this function (which I've altered a bit) on PHP.net.

Posted: Sat Dec 02, 2006 3:43 pm
by feyd
it'd be something like

Code: Select all

while first_needle in string from previous position
  update previous position via finding position of second_needle
  add the substring between the first_needle and second_needle to an array