user3050047
user3050047

Reputation: 23

Make first letter capital

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)

Upvotes: 2

Views: 210

Answers (5)

Madara&#39;s Ghost
Madara&#39;s Ghost

Reputation: 175098

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.

Upvotes: 0

Richard Schneider
Richard Schneider

Reputation: 35464

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; }

Upvotes: 5

Amal
Amal

Reputation: 76676

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

Upvotes: 3

aelor
aelor

Reputation: 11116

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

Upvotes: 0

user3383116
user3383116

Reputation: 392

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

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

Upvotes: -4

Related Questions