I am trying to minify an HTML string but also wrap the text at a certain character count. So I need a special function when the HTML string contains embedded CSS. I have tried using the php function “wordwrap” but its wrapping text within double quotes (“) and single quotes (‘) which breaks the display. For example, if we had the following string:
font-family: Arial, 'Helvetica Nueue', 'Times Roman'
Now if we do a wordwrap on this at say, 31, it will become:
font-family: Arial, 'Helvetica
Nueue', 'Times Roman'
And this will cause browsers to misinterpret the CSS string when loaded.
Does anyone know how or has written a wordwrap function that won’t wrap when the text is contained within quotes (single or double)?
Thanks!
UPDATE
Sorry for asking for just code. This is what I envision being done (which I am currently working on programming):
Loop through the CSS string and grab chunks of the string that are inbetween ; } or { if its close the break limit, add the substrings to an array. Once the loop is complete implode the array into a string using “\n” as the glue.
Anyone have a better/different approach?
The PHP
wordwrapfunction has some knowledge about specific ASCII characters.In your example text you do not want to allow the spaces inside of single quotes to wrap, so you can just replace spaces with non-breaking spaces.
wordwrapwill then not wrap at those any longer:This is a ASCII version for such a “nowrap” function.
As it only needs to be applied partially to the single-quoted parts, those parts need to be obtained. This can be easily done with a regular expression:
To apply the nowrap function onto the matches however, this needs a helper function to map the first matching group to the input value:
Then this can be easily applied:
You can then safely apply the
wordwrapfunction which for the examplewordwrap($subject, 31)will give the following output:You can also convert those back if you do not want to have these in your output.
The code in full: