13

I'm working with a mysqldump file that has escaped character sequences. I need to know the length of a string as its database value, but the dump has escape characters in it, which add length to the string.

I've used stripslashes() which properly un-escapes single- and double-quotes, but it doesn't touch the \r\n.

I'm concerned there are other escaped character sequences in there that I'm not aware of. Is there a function I can use that will give me the true length of the string as it would be in the database? If I have to build my own function, what other sequences should it handle?

Arnaud Le Blanc
  • 98,321
  • 23
  • 206
  • 194
user151841
  • 17,377
  • 29
  • 109
  • 171
  • Actually, stripslashes changes `\r\n` into `rn`. That adds 2 to the length of the string, which is a correct value, because `\r\n\` are actually two characters in the string, even though they aren't literally `rn`. Hm... – user151841 Aug 24 '11 at 15:55

2 Answers2

21

The strip c slashes() function does exactly that:

stripcslashes('foo\r\n');
Arnaud Le Blanc
  • 98,321
  • 23
  • 206
  • 194
2

You can use substr_count() to count characters in a string. Simply count how many backslashes are in the string:

$string = "... mysqldump string here ...";
$backslashes = substr_count($string, '\\');

That'll give you a rough count. To be 100% accurate, you'd have to count how many double backslashes there are, to account for literal backslashes, and adjust the count as appropriate.

Marc B
  • 356,200
  • 43
  • 426
  • 500