2

I have this code snippet, where I want to change the first letter to capital. But I couldn't manage make it working.

preg_replace('/(<h3[^>]*>)(.*?)(<\/h3>)/i', '$1'.ucfirst('$2').'$3', $bsp)

5 Answers5

5

Using regex to parse HTML is always difficult. To avoid PHP and regex, I suggest using CSS and the text-transform property.

h3 { text-transform: capitalize; }
Richard Schneider
  • 34,944
  • 9
  • 57
  • 73
3

Warning: HTML is not a regular language and cannot be properly parsed using a regular expression. Use a DOM parser instead.

$bsp = '<h3>hello</h3>';

$dom = new DOMDocument;
$dom->loadXML($bsp);

foreach ($dom->getElementsByTagName('h3') as $h3) {
    $h3->nodeValue = ucfirst($h3->nodeValue);
}

echo $dom->saveHTML();

Demo


But if you're absolutely sure that the markup format is always the same, you can use a regex. However, instead of preg_replace(), use preg_replace_callback() instead:

$bsp = '<h3>hello</h3>';

echo preg_replace_callback('/(<h3[^>]*>)(.*?)(<\/h3>)/i', function ($m) {
    return $m[1].ucfirst($m[2]).$m[3];
}, $bsp);

Demo

Community
  • 1
  • 1
Amal Murali
  • 75,622
  • 18
  • 128
  • 150
0

using a dom parser like this may be :

<?php
$html='<h3>hello world</h3>';
$dom = new DOMDocument;
$dom->loadHTML($html);
echo ucfirst($dom->getElementsByTagName('h3')->item(0)->nodeValue);

outputs :

Hello world
aelor
  • 10,892
  • 3
  • 32
  • 48
  • That only works on the first element. Basing on his initial question, it's safer to assume he wants it to work on all h3 elements. – Madara's Ghost Apr 28 '14 at 08:33
0

Using DOMXPath:

<?php

$html = 'HTML String <h3>whatever</h3>';
$dom = new DOMDocument;
$dom->loadHTML($html, LIBXML_HTML_NODEFDTD); //Don't add a default doctype.
$xpath = new DOMXPath($dom);
foreach ($xpath->query('//h3') as $h3) {
    $h3->nodeValue = ucfirst($h3->nodeValue);
}
echo $dom->saveHTML();

Will catch all h3s even if they aren't formatted exactly as you expect.

Madara's Ghost
  • 172,118
  • 50
  • 264
  • 308
-4

Does the first letter capital - echo ucfirst($str)

Makes the first letter of every word in a capital - echo ucwords($str)

user3383116
  • 392
  • 1
  • 7