Page 1 of 1

Put in seperate $var content whats in between *&&*

Posted: Mon Feb 21, 2011 1:10 am
by Peuplarchie
Good day to you all,
I'm looking for a way to retrieve the text in between *& &* and put it's content into a $var. for each occurrence with in a string.

$occu[0] = "dsfsdf";
$occu[1] = "10";
$occu[2] = "10sct";

Is there a way to do this ?


I know how to do it but not recusively.

Code: Select all

function get_string_between($string, $start, $end){
	$string = " ".$string;
	$ini = strpos($string,$start);
	if ($ini == 0) return "";
	$ini += strlen($start);
	$len = strpos($string,$end,$ini) - $ini;
	return substr($string,$ini,$len);
}

$parsed = get_string_between($tache, "*&", "&*");
$tache = str_replace("*&","<div class=\"progress-containers\"><div style=\"width:",$tache);
$tache = str_replace("&*","%\">$parsed</div></div>",$tache);

Can somebody can give me a tips ?

Re: Put in seperate $var content whats in between *&&*

Posted: Mon Feb 21, 2011 2:35 am
by cpetercarter

Code: Select all

<?php
$string = "somerandomtextd&fd7&somemoretext&gf4&some more random text";
$search = "/&([a-zA-Z0-9]+)&/";
preg_match_all($search, $string, $matches);
var_dump ($matches[1]);
?> 
The variable $matches[1] should contain an array of the sections of $string between & and &. The regex assumes that the sections you want to capture will contain only alphanumeric characters. You will need to adjust $search if you want, for example, to allow spaces in the captured text.

Re: Put in seperate $var content whats in between *&&*

Posted: Mon Feb 21, 2011 4:59 pm
by Peuplarchie
Nice ,Ok, I see, after looking at it, testing it, I do understand but not yet how to implement it with a foreach loop.

Let says instead I use index 0 to give me the whole piece and I replace the whole string with anther with the "number" index 1 with the formated html. See code

Code: Select all

preg_match_all('/\*&([a-z0-9]+)&\*/i',$tache,$out, PREG_SET_ORDER);
echo $out[0][0] . ", " . $out[1][0] . ", " . $out[2][0] . ", " . $out[3][0] . ", " . $out[4][0] . "\n";
$i = 0;
foreach ($out[$i][0] as &$value) {
$value = str_replace("*&","<div class=\"progress-containers\"><div style=\"width:",$value);
$value = str_replace("&*","%\">$value[$i][1]</div></div>",$value);
    $i++;
}