Hi,
I have a function which converts text into a header format:
Its nice because I can chose deliminators and exception
This is the string version:
function titleCase_str($string){
$delimiters = array(" ", "-", ".", "'", "O'", "Mc");
$exceptions = array("and", "to", "of", "das", "dos", "I", "II", "III", "IV", "V", "VI");
$string = mb_convert_case($string, MB_CASE_TITLE, "UTF-8");
foreach ($delimiters as $dlnr => $delimiter) {
$words = explode($delimiter, $string);
$newwords = array();
foreach ($words as $wordnr => $word) {
if (in_array(mb_strtoupper($word, "UTF-8"), $exceptions)) {
// check exceptions list for any words that should be in upper case
$word = mb_strtoupper($word, "UTF-8");
} elseif (in_array(mb_strtolower($word, "UTF-8"), $exceptions)) {
// check exceptions list for any words that should be in upper case
$word = mb_strtolower($word, "UTF-8");
} elseif (!in_array($word, $exceptions)) {
// convert to uppercase (non-utf8 only)
$word = ucfirst($word);
}
array_push($newwords, $word);
}
$string = join($delimiter, $newwords);
}//foreach
return $string;
}
This works fine on a string like this:
$the_title = "this-that is. a test of the Mcdougal title";
$test_title_out = titleCase_str($the_title);
I get this output:
This-That Is. A Test of The McDougal Title
But I only want to apply this titleCase to titles within
a body of text.
So I have tried to convert the function to use an array input:
function titleCase($matches){
$string = $matches[1];
$delimiters = array(" ", "-", ".", "'", "O'", "Mc");
$exceptions = array("and", "to", "of", "das", "dos", "I", "II", "III", "IV", "V", "VI");
$string = mb_convert_case($string, MB_CASE_TITLE, "UTF-8");
foreach ($delimiters as $dlnr => $delimiter) {
$words = explode($delimiter, $string);
$newwords = array();
foreach ($words as $wordnr => $word) {
if (in_array(mb_strtoupper($word, "UTF-8"), $exceptions)) {
// check exceptions list for any words that should be in upper case
$word = mb_strtoupper($word, "UTF-8");
} elseif (in_array(mb_strtolower($word, "UTF-8"), $exceptions)) {
// check exceptions list for any words that should be in upper case
$word = mb_strtolower($word, "UTF-8");
} elseif (!in_array($word, $exceptions)) {
// convert to uppercase (non-utf8 only)
$word = ucfirst($word);
}
array_push($newwords, $word);
}
$string = join($delimiter, $newwords);
}//foreach
return $string;
}
And now to use the function in the preg_replace_callback()
$test = "now for a test. [hd2]this is header2[/hd] test! does THIS [hd3] this is header3 [/hd]THING work? we will soon know # willl we not ? see you soon";
$test_output2 = preg_replace_callback(
"/(\hd[1-6](.+?)\[\/hd\])/",
"titleCase",
$test);
But my headings don't get converted
I get this output:
now for a test. [hd2]this is header2[/hd] test! does THIS [hd3] this is header3 [/hd]THING work? we will soon know # willl we not ? see you soon
Can anyone see what I have done wrong ?
Thanks.
.