Adding html tags to a string programmatically

Hello Sitepoint’ers,

 I need to put together a couple of functions that do the following:-

The first takes any given string and adds and opening span tag to the front, and a closing tag to the end.

The second takes another string, and adds span tags to the very first letter in the string.

If someone could point me in the right direction I would be most apprecative!

Kind regards,

:slight_smile:

Well #1 is just string concatenation. ( which is . in php)
#2 is also string concatenation, but with a bit of [FPHP]substr[/FPHP] thrown in.

HI, thanks for your reply. I forget to mention that I only want these tags added if they dont already exist as part of the string

Ah. Now we’re getting a bit more sensitive…

“if they dont already exist as part of the string”… does that mean ANYWHERE in the string? or specifically at the beginning and ends?

Scrap that, specifically where I want them to be added originally. Its kinda like a saftey net that if my users dont add them, they will be added automatically before submitting to the database (I hope that makes sense)

Yup.

Well, since we’re working with just one tag, wont be that hard.
substr the left and right sides of the string (Hint: the Start parameter can take a negative integer.), and see if they are a span tag. If not, slap the tag on.

Ok Sir, I will try that thanks

This will do what you’re asking.

$string = 'This is a string.';
$first_letter = substr($string, 0, 1);
$remaining_string = substr($string, 1);

if(substr($string, 0, 5) != '<span') {
 $string = '<span><span>'.$first_letter.'</span>'.$remaining_string;
}
if(substr($string, -7) != '</span>') {
 $string .= '</span>';
}

If you’re trying to style the first letter, however, you’d be better off using the CSS pseudo-class :first-letter:

$string = 'This is a string.';

if(substr($string, 0, 5) != '<span') {
 $string = '<span class="some_class">'.$string;
}
if(substr($string, -7) != '</span>') {
 $string .= '</span>';
}
span.some_class:first-letter {
/* some styling */
}

Brilliant post, ill try that in the morning thanks again! :slight_smile: