views:

57

answers:

4

Im a bit stumped on how to make a string uppercase in php while not making the markup uppercase.

So for example:

<p>Chicken &amp; <a href="/cheese">cheese</a></p>

Will become

<p>CHICKEN &amp; <a href="/cheese">CHEESE</a></p>

Any advice appreciated, thanks!

+2  A: 

Well you could use the DOM class and transform all text with it.

EDIT: or you could use this css:

.text{
    text-transform: uppercase;
}

as GUMBO suggested

ITroubs
+1  A: 

Parse it, then capitalize as you like.

Ignacio Vazquez-Abrams
why parsing with a PHP written parser wen PHP itself has DOM XML functions since version 4 and a whole DOM class since PHP 5?
ITroubs
A: 

I would be tempted to make the whole string uppercase...

$str = strtoupper('<p>Chicken &amp; <a href="/cheese">cheese</a></p>');

...And then use a preg_match() call to re-iterate over the HTML tags (presuming the HTML is valid) to lowercase the HTML tags and their attributes.

Martin Bean
And what if there already are some uppercase letters inside the tags?
Gumbo
This approach is very error-prone for complex HTML code. I wouldn't recommend it.
Lekensteyn
Ghommey
apache also makes a big difference between a picture.jpg and a Picture.jpg and if you transform the Picture.jpg into a picture.jpg in a <img > tag you will run into problems verry fast
ITroubs
+4  A: 

The following will replace all DOMText node data in the BODY with uppercase data:

$html = <<< HTML
<p>Chicken &amp; <a href="/cheese">cheese</a></p>
HTML;

$dom = new DOMDocument;
$dom->loadHTML($html);
$xPath = new DOMXPath($dom);
foreach($xPath->query('/html/body//text()') as $text) {
    $text->data = strtoupper($text->data);
}
echo $dom->saveXML($dom->documentElement);

gives:

<html><body><p>CHICKEN &amp; <a href="/cheese">CHEESE</a></p></body></html>

Also see

Gordon
+1 for example..
ITroubs