is there a function that will allow me to do the following:
开发者_C百科$template = "{name}:{city}-{state}"
$string = "Tom:Some CityPlace-CA"
$out = function_I_am_looking_for($template,$string);
when $out returns
Array(
[name] => Tom
[city] => Some CityPlace
[state] => CA
)
Does such a function exist?
-------- EDIT -----------
So the people have spoken, and since I dont like seeing something like this die, I will conclude. No built in function exists, however I did mock up one, and it does work. Feel free to refine, please comment you edits.
function genaric_match($template,$string,$varStart="{{",$varEnd="}}"){
$template = str_replace($varStart,"|~|`",$template);
$template = str_replace($varEnd,"`|~|",$template);
$t=explode("|~|",$template);
$temp="";
$i=0;
foreach ($t as $n=>$v){
$i++;
if (($i==count($t)||($i==(count($t)-1)&&$t[$n+1]==""))&&substr($v,0,1)=="`"&&substr($v,-1)=="`"){
//Last Item
$temp.="(?P<".substr($v,1,-1).">.++)";
}elseif(substr($v,0,1)=="`"&&substr($v,-1)=="`"){
//Search Item
$temp.="(?P<".substr($v,1,-1).">[^".$t[$n+1]."]++)";
}else{
$temp.=$v;
}
}
$temp="~^".$temp."$~";
preg_match($temp, $string, $matches);
return $matches;
}
This example
print_r(genaric_match("{{name}}:{{city}}-{{state}}","Tom:Some CityPlace-CA"));
Returns
Array
(
[0] => Tom:Some CityPlace-CA
[name] => Tom
[1] => Tom
[city] => Some CityPlace
[2] => Some CityPlace
[state] => CA
[3] => CA
)
Yes, it's called preg_match
. But you obviously need to write a regex for it. (If your question is, whether there is a magic recognize-any-pattern-without-even-knowing-it's-syntax function, then the answer is: No.)
preg_match('~^(?P<name>[^:]++):(?P<city>[^-]++)-(?P<state>.++)$~', $string, $matches);
var_dump($matches);
There's no such function in PHP "out of the box", but it would be fairly trivial to write one, as there are quite a few functions such as...
- explode
- preg_replace
- parse_string
- etc.
...that you could use to create one.
However, it has to be said that using PHP (which is to a large extent a template language) to create another template language seems an odd choice.
精彩评论