How to convert UPPERCASE text to Title Case using CSS - php

If you're reading this you probably noticed that the CSS property text-transform:capitalize; does not convert THIS into This. Instead the, non-initial characters remain capitalized, so the transformation has no effect in this case. So how can we achieve this result?
I've seen this asked often and most answers are quick to promote using javascript to accomplish this. This will work, but it is unnecessary if you are writing or customizing a template/theme for a PHP CMS like Wordpress, Drupal, or Joomla.

To some degree you can achieve this with CSS using the pseudo class ::first-letter and should work all the way back to IE 5.5 :-(
NOTE: this is very dependent on your html structure, and will not work in all cases, but can be useful from time to time. Hit "run code snippet" to the see the result below.
.progTitle {
text-transform: lowercase;
}
.progTitle::first-letter {
text-transform: uppercase;
}
<p class="progTitle">THIS IS SOME TEST TEXT IN UPPERCASE THAT WILL WORK. </p>
<p class="progTitle">this is some test text in lowercase that will work. </p>
<p class="progTitle"><i class="fa fa-bars"></i> THIS WILL NOT WORK </p>

The bad news is that there is no such thing as text-transform : title-case which would guarantee the result to be title cased. The good news is that there IS a way to do it, which doesn't require javascript (as is often suggested for this situation). If you are writing a theme for a CMS you can use strtolower() and ucwords() to convert the relevant text to title case.
BEFORE (THIS DOESN'T WORK):
<style>
.title-case{ text-transform:capitalize; }
</style>
<span class="title-case">ORIGINAL TEXT</span>
AFTER:
<?php echo ucwords( strtolower('ORIGINAL TEXT') ); ?>
If you are writing a theme, you'll probably be working with variables instead of text strings, but the function and the concept work the same way. Here's an example using the native Wordpress function get_the_title() to return the page title as a variable:
<?php
$title = get_the_title();
$title = strtolower($title);
$title = ucwords($title);
<h1>
<?php echo $title;
</h1>
?>
Hope this helps someone. Happy coding.

The best way to do this is to have a class or element for the particular text and use this CSS rule:
.my_text {
text-transform: capitalize;
}
<p class="my_text">hello stackoverflow!!</p>
h1 {
text-transform: capitalize;
}
<h1>hello stackoverflow!!</h1>

Here is a working example in a Joomla 1.5.22 website running Virtuemart 1. The purpose is to take a string which is originally UPPERCASE, and convert it to Proper Case.
UPPERCASE:
<?php echo $list[$i]->name; ?>
Proper Case:
<?php echo ucwords( strtolower($list[$i]->name) ); ?>

This can be achieved with one simple rule:
text-transform: capitalize;

You just write text-transform: none;

Related

Using html with style tags in php code

I have been given the following as a template for use in an email. I am using phpmailer to mail it out, but am having a problem with the way style tags begin and end as they are conflicting with the php. If I go through thier template, I could move all the styles into a seporate style sheet or use classes and put the styles at the top of the page, but I dont want to do this unless I really have to.
Below is a generic example of what is going wrong with the code. The font names are wrapped in "s so the opening and closing tags of the style are 's , these 's are clashing with the opening and closing tags of php. I cant seem to find a way round it though as if I put,
style=""font-name","another-font"" this wont work, if I use 's at all php is then screwed up.
What is happening is in php mailer the form contents are declared as
$body = '<span style='font-size: 13.5pt;font-family:"Georgia","serif";color:white'>some content</span></html>';
You need to escape your quotes. Example:
$body = '<div style=\'background:#000;\'><p>srs business here</p></div>';
You can also work with HEREDOC (http://www.php.net/manual/en/language.types.string.php#language.types.string.syntax.heredoc). This will save you a lot of messy code.
Example:
$string = <<<SOMELABEL
Here you can put your <span style='font-family: arial, helvetica, sans-serif'>formatted code</span>
SOMELABEL;
And then:
$body = $string;
Don't do this.
Your issue is not using HTML/CSS in PHP, it's just that your strings are basically un-stringing themselves, you need to escape the quotes as #ddubs said.
However, the elaborate on the "Don't do this", you shouldn't be mixing your HTML and PHP code like this. Although it's of course not required you should be separating out your logic from presentation as much as possible.
You can simply jump out of PHP with the closing tag, and jump back in when you need it, for example (based on yours):
// code code code ...
?>
<span style="font-size: 13.5pt; font-family: 'Georgia', serif; color: white">
<?php echo $variable_from_code ?>
</span></html>
Whilst I'm on the whole crusade, you also shouldn't really be using inline styles ;-)

Creating and App using PHP, Mysql, and jquery and i am stuck

I would like to create an app that writes a basic music chord chart to a database and pulls it out onto a different page.
I know the basic to intermediate concepts of inserting and returning data to a database but I am having trouble on this one.
In a textarea I would like the member to be able to insert into the database like so...
{C}I`ve {F}been {G}though {A}the {C}desert
The Letters inside the brackets being the chords and the words outside of the brackets being the lyrics.
This is not the problem though, I know how to do that.
The problem is, I would like the {Chords} to be placed directly above the letter they are preceding while also giving them a class that would allow me to change the font color, size, and weight when rendered on page.
I have been thinking that there is a way to do this with tables, str_replace, and strTok but I cannot figure it out.
Any suggestions?
use regular expression to extract content of {} into an array
str_replace {} to blank (space), in a way you will have plain text except chords letter
use html css, put Chords letters in span tag.change css of span, so it position above the letter. i.e. span position is absolute and parent container position to relative.
if you want to save those chords into table , you can as its already in array
Hope this helps, best of luck
Working with HTML tables can be a real pain. Here's how you could do the HTML part of it without using tables:
<style>
.phrase { display: inline-block; }
.chord { font-size: 20px; }
.lyrics { font-size: 12px; margin-right: 1em; }
</style>
<div class="phrase">
<span class="chord">C</span><br>
<span class="lyrics">I've</span>
</div>
And with a little PHP mixed in:
<?php
$phrases = array(
array('chord' => 'C', 'lyrics' => "I've"),
array('chord' => 'F', 'lyrics' => 'been'),
);
?>
<?php foreach($phrases as $phrase): ?>
<div class="phrase">
<span class="chord"><?php echo $phrase['chord']; ?></span><br>
<span class="lyrics"><?php echo $phrase['lyrics']; ?></span>
</div>
<?php endforeach; ?>
As far as saving/retrieving from the database. You could do some fancy regular expression/string replace thing, but that's probably more work than you really need to do. Just keep it simple and create a structure like this:
Songs Example
--------- -----------
id (PK) 1234
song_title I've been through the desert
Phrases
-----------
id (PK) 1
song_id (FK) 1234
chord C
lyrics I've
order 1
You'll have a lot more rows in your Phrases table, but it will be a lot easier to work with.
Also, as a final, biased, piece of advice: check into Ruby on Rails. I started out learning PHP and wished I would have learned Ruby on Rails earlier in my career. There are a lot of ways that Ruby on Rails makes it easy for a beginner to get started programming.

Replacing // comments with /* comments */ in PHP

I'm creating a CSS generator in PHP which uses CSSX (yep, they are my idea) files (with a special syntax). One feature is 'short comments':
body
{
font-family: Georgia; //I really like this font!
}
Now I want to replace this comment with a /* ... */ comment, so the output is like this:
body
{
font-family: Georgia; /*I really like this font!*/
}
How can I do this? Thanks,
P.S. The complete CSSX file is read into one string variable.
P.P.S This q is answered. To fix the url('//server/etc.cssx') problem, use this:
$file = preg_replace('~[^"\'\(]//([^\r\n]*)[^"\'\)]~', '/*$1*/', $file);
A regexp should do the trick:
$str = preg_replace('_//(.*)$_m', '/*$1*/', $str);
This won't take into account quoted strings - if you're using something crazy like
background-image: url('//my-server/my.jpg');
then it's going to think that's a comment.
If this is a problem then you're better off writing a proper parser.
<? preg_replace('#//(.*)$#', '/*$1*/', $cssx); ?>
Greg's expression has two problems: first, 'm' and '$' are superfluous, second it doesn't handle carriage returns correctly (in case your system uses them).
A better expression appears to be
preg_replace('~//([^\r\n]*)~', '/*$1*/', $str);

Count words like Microsoft Word does

I need to count words in a string using PHP or Javascript (preferably PHP). The problem is that the counting needs to be the same as it works in Microsoft Word, because that is where the people assemble their original texts in so that is their reference frame.
PHP has a word counting function (http://php.net/manual/en/function.str-word-count.php) but that is not 100% the same as far as I know.
Any pointers?
The real problem here is that you're trying to develop a solution without really understanding the exact requirements. This isn't a coding problem so much as a problem with the specs.
The crux of the issue is that your word-counting algorithm is different to Word's word-counting algorithm - potentially for good reason, since there are various edge-cases to consider with no obvious answers. Thus your question should really be "What algorithm does Word use to calculate word count?" And if you think about this for a bit, you already know the answer - it's closed-source, proprietary software so no-one can know for sure. And even if you do work it out, this isn't a public interface so it can easily be changed in the next version.
Basically, I think it's fundamentally a bad idea to design your software so that it functions identically to something that you cannot fully understand. Personally, I would concentrate on just developing a sane word-count of your own, documenting the algorithm behind it and justifying why it's a reasonable method of counting words (pointing out that there is no One True Way).
If you must conform to Word's attempt for some short-sighted business reason, then the number one task is to work out what methodology they use to the point where you can write down an algorithm on paper. But this won't be easy, will be very hard to verify completely and is liable to change without notice... :-/
Bit of a mine-field as MS word counts are considered wrong and unreliable by profesionals who depend on word counts -- journalists, translators, and, lawers who are often involved in legal procedures where motions and submisions must be less than a specific number fo words.
Having said that this article-
http://dotnetperls.com/word-count
describes a pretty good regex algorithm implemented in C# -- but should be faily easy to transalate into php.
I think his small inaccuracies are based on two factors -- MS Word misses out words not conatined in "regular paragraphs" so footnotes, text box and table wrapped words may or may not be counted. Also I think the EVIL smart quotes feature messing with hypens may affect the results. So it may be worth changing all the 'el-dash' and 'em-dash' characters back to the normal minus sign.
The following JS code gives a word count of 67. OpenOffice gives the same number.
str = "I need to count words in a string using PHP or Javascript (preferably PHP). The problem is that the counting needs to be the same as it works in Microsoft Word, because that is where the people assemble their original texts in so that is their reference frame. PHP has a word counting function (http://php.net/manual/en/function.str-word-count.php) but that is not 100% the same as far as I know.";
wordCount = str.split(/\s+/g).length;
function countWords( $text )
{
$text = preg_replace('![^ \pL\pN\s]+!u', '', strtolower($text));
$text = trim( preg_replace('![ \s]+!u', ' ', $text) );
$count = count( explode(' ', $text) );
return $count;
}
you can use this code for word count
<title>Untitled Document</title>
<script type="text/javascript" src="mootools.svn.js"></script>
<script type="text/javascript">
window.addEvent('domready', function()
{
$('myInput').addEvent('keyup', function()
{
max_chars = 0;
current_value = $('myInput').value;
current_length = current_value.length;
remaining_chars = max_chars+current_length;
$('counter_number').innerHTML = remaining_chars;
if(remaining_chars<=5)
{
$('counter_number').setStyle('color', '#990000');
} else {
$('counter_number').setStyle('color', '#666666');
}
});
});
</script>
<style type="text/css">
body{
font-family:"Lucida Grande", "Lucida Sans Unicode", Verdana, Arial, Helvetica, sans-serif;
font-size:12px;
color:#000000;
}
a:link, a:visited{color:#0066CC;}
label{display:block;}
.counter{
font-family:Georgia, "Times New Roman", Times, serif;
font-size:16px;
font-weight:bold;
color:#666666
}
</style>
</head>
<body>
<label for="myInput">Write something here:</label>
<input type="text" id="myInput" maxlength="20" />
<span id="counter_number" class="counter">20</span>
Remaining chars
and download the mootools library...

How to wrap long lines without spaces in HTML?

If a user types in a long line without any spaces or white space, it will break formating by going wider than the current element. Something like:
HAHAHAHAHAHAHAHAHAHAHAHAHAHAHAHAHAHAHAHA.............................................................................................................................................
I've tried just using wordwrap() in PHP, but the problem with that is if there is a link or some other valid HTML, it breaks.
There seems to be a few options in CSS, but none of them work in all browsers. See word-wrap in IE.
How do you solve this problem?
in CSS3:
word-wrap:break-word
I was trying to solve the same problem and I found de solution here:
http://perishablepress.com/press/2010/06/01/wrapping-content/
Solution: adding to the container the following CSS properties
div {
white-space: pre; /* CSS 2.0 */
white-space: pre-wrap; /* CSS 2.1 */
white-space: pre-line; /* CSS 3.0 */
white-space: -pre-wrap; /* Opera 4-6 */
white-space: -o-pre-wrap; /* Opera 7 */
white-space: -moz-pre-wrap; /* Mozilla */
white-space: -hp-pre-wrap; /* HP Printers */
word-wrap: break-word; /* IE 5+ */
}
The idea is using them all so you get better cross-browser compatibility
Hope this helps
I like to use the overflow: auto CSS property/value pairing. This will render the parent object the way you'd expect it to appear. If the text within the parent is too wide, scrollbars appear within the object itself. This will keep the structure the way you want it to look and provide the viewer with the ability to scroll over to see more.
Edit: the nice thing about overflow: auto compared to overflow: scroll is that with auto, the scrollbars will only appear when overflowing content exists. With scroll, the scrollbars are always visible.
I haven't personally used it, but Hyphenator looks promising.
Also see related (possibly duplicate) questions:
word wrap in css / js
Who has solved the long-word-breaks-my-div problem? (hint: not stackoverflow)
I'm surprised that nobody has mentioned one of my favorite solutions to this problem, the <wbr> (optional line-break) tag. It's fairly well-supported in browsers and essentially tells the browser that it can insert a line-break if it's necessary. There's also the related zero-width space character, ​ with the same meaning.
For the use case mentioned, displaying user comments on a web page, I would assume that there is already some output formatting to prevent injection attacks, etc. So it's simple to add these <wbr> tags every N characters in words that are too long, or in links.
This is especially useful when you need control over the format of the output, which CSS doesn't always let you do.
I would put the post in a div that would have a fixed width setting overflow to scroll (or to hide completely depending on the content).
so like:
#post{
width: 500px;
overflow: scroll;
}
But that's just me.
EDIT: As cLFlaVA points out... it is better to use auto then scroll. I do agree with him.
There is no "perfect" HTML/CSS solution.
The solutions either hide the overflow (ie scrolling or just hidden) or expand to fit. There is no magic.
Q: How can you fit a 100cm wide object into a space only 99cm wide?
A: You can't.
You can read break-word
EDIT
Please check out this solution
How to apply a line wrap/continuation style and code formatting with css
or
How to prevent long words from breaking my div?
I dodge the problem by not having my right sidebar fixed like that :P
Here's what I do in ASP.NET:
Split the text field on spaces to get all the words
Iterate the words looking for words that are longer than a certain amount
Insert every x characters (e.g. every 25 characters.)
I looked at other CSS based ways of doing this, but didn't find anything that worked cross-browser.
based on Jon's suggestion the code that I created:
public static string WrapWords(string text, int maxLength)
{
string[] words = text.Split(' ');
for (int i = 0; i < words.Length; i++)
{
if (words[i].Length > maxLength) //long word
{
words[i] = words[i].Insert(maxLength, " ");
//still long ?
words[i]=WrapWords(words[i], maxLength);
}
}
text = string.Join(" ", words);
return (text);
}
I didn't want to add libraries to my pages just for word breaking.
Then I wrote a simple function which I provide below, hope it helps people.
(It is breaking by 15 characters, and applying "& shy;" between, but you can change it easily in the code)
//the function:
BreakLargeWords = function (str)
{
BreakLargeWord = function (word)
{
var brokenWords = [];
var wpatt = /\w{15}|\w/igm;
while (wmatch = wpatt.exec(word))
{
var brokenWord = wmatch[0];
brokenWords.push(brokenWord);
if (brokenWord.length >= 15) brokenWords.push("­");
}
return brokenWords.join("");
}
var match;
var word = "";
var words = [];
var patt = /\W/igm;
var prevPos = 0;
while (match = patt.exec(str))
{
var pos = match.index;
var len = pos - prevPos;
word = str.substr(prevPos, len);
if (word.length > 15) word = BreakLargeWord(word);
words.push(word);
words.push(match[0]);
prevPos = pos + 1;
}
word = str.substr(prevPos);
if (word.length > 15) word = BreakLargeWord(word);
words.push(word);
var text = words.join("");
return text;
}
//how to use
var bigText = "Why is this text this big? Lets do a wrap <b>here</b>! aaaaaaaaaaaaa-bbbbb-eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee";
var goodText = BreakLargeWords(bigText);
Add the Zero width space (​) to the string and it will wrap.
Here is a Javacript example:
let longWordWithOutSpace = 'pneumonoultramicroscopicsilicovolcanoconiosis';
// add ​ between every character to make it wrap
longWordWithOutSpace.split('').join('​');
! I did not wanted to make my code more complex with Javascript.
my developing Env was Blazor and UI was for Smartphone.
the Code had a list of file names and some of them where a very long name without space or any other helping Char.
for me this works:
https://developer.mozilla.org/en-US/docs/Web/CSS/overflow-wrap
overflow-wrap: anywhere;
" overflow-wrap: normal; " not work becase it needs space in strings to wrap.
"overflow-wrap: break-word;" not worked for me maybe because it was not a word or something else. I am not sure!
I have posted a solution which uses JavaScript and a simple Regular Expression to break long word so that it can be wrapped without breaking your website layout.
Wrap long lines using CSS and JavaScript
I know that this is a really old problem and since I had the same problem I searched for a easy solution.
As mentioned in the first post I decided to use the php-function wordwrap.
See the following code example for information ;-)
<?php
$v = "reallyreallyreallylonglinkreallyreallyreallylonglinkreallyreallyreallylonglinkreallyreallyreallylonglinkreallyreallyreallylonglinkreallyreallyreallylonglink";
$v2 = wordwrap($v, 12, "<br/>", true);
?>
<html>
<head>
<title>test</title>
</head>
<body>
<table width="300" border="1">
<tr height="30">
<td colspan="3" align="center" valign="top">test</td>
</tr>
<tr>
<td width="100"><?php echo $v2; ?></td>
<td width="100"> </td>
<td width="100"> </td>
</tr>
</table>
</body>
</html>
Hope this helps.

Categories