Forum Moderators: coopster

Message Too Old, No Replies

PHP code to automatically change font of first letter of an article

possible with strreplace?

         

petra

8:59 am on Oct 8, 2006 (gmt 0)

10+ Year Member



I've only recently moved to building websites using PHP and MYSQL and was wondering if this is possible.

Basically I want the article to automatically be outputed with the first letter of the first Paragraph to be in a slightly larger font with a different color.

Can I accomplish this using the strreplace function in PHP?

MattAU

9:19 am on Oct 8, 2006 (gmt 0)

10+ Year Member



I don't think str_replace would help...

Something like this would work though:

$paragraph = 'Here\'s the paragraph text';

// Add the font change to the first char of $paragraph
$first_char = '<font size="3">' . $paragraph[0] . '</font>';

// Combine $first_char and the $paragraph string starting from the second char
$new_paragraph = $first_char . substr($paragraph,1);

petra

9:36 am on Oct 8, 2006 (gmt 0)

10+ Year Member



Perfect, thanks so much MattAU :-)

petra

12:30 pm on Oct 8, 2006 (gmt 0)

10+ Year Member



BTW, is it possible to make it the first letter and not the first character? Some of my articles start with a <p> tag.

Frank_Rizzo

2:10 pm on Oct 8, 2006 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



How many articles do you have?

Can you not just edit the database entries? You say some of them start with a <p>. Just edit them all so they start with a <font ...

petra

2:29 pm on Oct 8, 2006 (gmt 0)

10+ Year Member



Yes I can, and thats what I've done so far, but as my articles are submitted by third parties (can't control their submissions), I wanted to see if there is a way to do it automatically so that the first letter is formated and not the first character

eelixduppy

2:43 pm on Oct 8, 2006 (gmt 0)



I guess you should use regex then:

$pattern = "/([a-zA-Z])/";
$formatted = preg_replace($pattern,"<font size='10px'>$1</font>",$string,1);
echo $formatted;

Good luck!

petra

2:50 pm on Oct 8, 2006 (gmt 0)

10+ Year Member



Thanks eelixduppy, that worked wonderfully!
What can we all do without WW?
Thanks all!

MattAU

11:26 pm on Oct 8, 2006 (gmt 0)

10+ Year Member



I'm not that great with regex, but I don't think that will work because it'll match the p in <p>, the h in <h1> etc.

I think this pattern will work, but you might want to test it a bit.

$pattern = "/(?<!\<[a-zA-Z1-6])([a-zA-Z0-9])(?![a-zA-Z1-6]*>)/";

Note that this will match the first letter / number outside of a basic html tag, so if the paragraph starts with a quotation mark or something else it may look a little funny. You could modify the regex to include this, but that's a bit harder... :)

The pattern also won't work on tags with attributes, such as <p class="style">

[edited by: MattAU at 12:06 am (utc) on Oct. 9, 2006]