Showing posts with label php. Show all posts
Showing posts with label php. Show all posts

Thursday, December 19, 2013

Double character to single with regex

How to unescape string, that is escaped doubling some character?

For example, CSV files format doubles double quotes, and wraps entire value with double quotes, so the string

My "fat" string!

becomes

"My ""fat"" string!"

To unescape that, I have to replace doubled double quotes with single double quotes, and remove single double quotes.

" ->
"" -> "

This is regex I need to use:
/"("{0,1})/
and replace with content of capturing group.

Example code for PHP:


// Ansi 
$s = preg_replace('/"("{0,1})/', '$1', '"My ""fat"" string!"');
 
// Unicode 
mb_regex_encoding('UTF-8');  
$s = mb_ereg_replace('/"("{0,1})/', '\\1', '"My ""fat"" string!"');

Saturday, June 18, 2011

PHP cut string properly

Common problem with PHP development is when you cut a non-latin string, it has strange symol at the end, looking like "�".

It's all because string is in Unicode format(mainly utf-8), however a substr function only works with single-byte encodings.

Instead of using substr, you must use mb_substr.

substr($string, $length, $count)
replace to
mb_substr($string, $length, $count, 'utf-8')