johnuk
September 12, 2011, 3:59pm
1
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,
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.
johnuk
September 12, 2011, 4:07pm
3
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?
johnuk
September 12, 2011, 4:15pm
5
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.
johnuk
September 12, 2011, 4:21pm
7
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 */
}
johnuk
September 12, 2011, 9:46pm
9
Brilliant post, ill try that in the morning thanks again!