Php isprint equivalent

People continually give me “Save as Text” output from Microsoft word–to use as text fragments inside a web page or a CMS. That output is seldom what I want, however, Word’s text output usually contains numerous binary characters that end up looking like black diamonds with a question mark inside the diamond, or some other such not-printable output.

In C I can loop through all the characters in a string and say:

if(isprint(ch) || ch == ’
')
fputc(ch, out_fp);

How do I do the same thing in PHP?

Ooo thanks Salathe.

You could probably emulate it with something like:-


<?php
function isprint($char){
  $controlChars = array_merge(
    range(0, 31),
    array(127)
  );
  return in_array(ord($char), $controlChars);
}

if(isprint($char) || $char === "\
"){
  fputs($fp, $char);
}

You could use a regular expression to remove all non-printing, non-newline characters with preg_replace().

$cleaned = preg_replace('/[^\
[:print:]]/', '', $subject);

If you need to check each character, or more closely emulate your C code, then use the ctype_print() function to check if the character is printable. ctype_print() calls the C isprint() function under the hood. (:


if (ctype_print($ch) || $ch === "\
") {
    fwrite($out_fp, $ch);
}