RD Ward
RD Ward

Reputation: 6737

Text wrap nightmare in PHP after PREG_REPLACE

Provinces is a group_concat of all the individual records that contain province, some of which are blank. So, when I encode:

$provinces = ($row['provinces']);

echo "<td>".wordwrap($provinces, 35, "<br />")."</td>";

This is what the result looks like:

Minas Gerais,,,Rio Grande do

Sul,Santa Catarina,Paraná,São Paulo

However, when I try to preg_replace out some of the nulls, and add some spaces with this expression:

$provinces = preg_replace($patterns, $replaces, ($row['provinces']));

echo "<td>".wordwrap($provinces, 35, "<br />")."</td>";`

This is what I get!!! :(

Minas Gerais, Rio Grande do

Sul, Santa

Catarina, Paraná, São Paulo

The output is very unnatural looking.

BTW: Here are the search and replace arrays:

$patterns[0] = '/,,([,]+)?/';       $replaces[0] = ',&nbsp;';
$patterns[1] = '/^,/';              $replaces[1] = '';
$patterns[2] = '/,$/';              $replaces[2] = '';
$patterns[3] = '/\b,\b/';           $replaces[3] = ',&nbsp;';
$patterns[4] = '/\s,/';             $replaces[4] = ',&nbsp;';

UPDATE: I even tried to change Paraná to Parana

Minas Gerais, Rio Grande do

Sul, Santa

Catarina, Parana, São

Paulo

Upvotes: 0

Views: 394

Answers (2)

David Weinraub
David Weinraub

Reputation: 14184

Is the wordwrap() really necessary? It sounds like you are rendering this content into a table cell of some fixed width and you don't want individual entries to split across lines.

If this inference is correct - and if none of your entries is actually so long that forcing it to a single line will break your layout - then how about this: explode() on commas into an array, remove the whitespace-only entries, replace normal spaces in each array entry with &nbsp;, and implode() back on , (a comma followed by a space). Then let the rendering browser break lines wherever it needs.

Upvotes: 0

Jason McCreary
Jason McCreary

Reputation: 72971

Don't use &nbsp; as the replacement. wordwrap() considers that 6 characters. It doesn't interpret the HTML entity. That's why your lines are breaking funny. If you want &nbsp; replace spaces after you wordwrap()

Also, your first pattern should be:

// match one or more commas together
$patterns[0] = '/,+/';

Upvotes: 1

Related Questions