I think one solution is to use a callback function to sort out which is an integer and which is a string.
PHP Code:
<?php
// set up some test strings
$strings[] = "The string is {container 1 basic} but could also contain {container advanced 99} for example";
$strings[] = "This should fail {container 1111 basic}"; // > 999
$strings[] = "This should fail {11 basic}"; // no container word
$strings[] = "This should fail {container 11 basic "; // missing end bracket
$strings[] = "This should fail { container 11 basic} "; // space prior to first bracket
$strings[] = "This should fail container 11 basic}"; // missing first bracket
$strings[] = "Should THIS fail {container 11 22}, or what should it do then?"; // a quandry?
$strings[] = "Should THIS fail {container silly basic}"; // ditto
// create the callback function
function make_divs($matches)
{
if( (int)$matches[1] > 0 ){
$id = $matches[1];
$class = $matches[2];
}else{
$id = $matches[2];
$class = $matches[1];
}
return "<div class=$class><a href=index.php?id=$id></a></div>";
}
// loop through the test cases, view page source to see the results properly
foreach( $strings as $string){
echo preg_replace_callback(
"#{container (\d{1,3}|[a-z]*) ([a-z]*|\d{1,3})}#",
"make_divs",
$string) , PHP_EOL;
}
?>
At its simplest that should work, but you will notice that the LAST TWO example strings possibly should fail, but do not -- as things stand, in order to keep the solution simple to follow.
The more varied and real worldly your test strings are the more complex the solution will probably end up becoming.
I leave it there because it is now up to you to post the test cases showing where you expect to pass and where you expect to fail.
HTH
Bookmarks