Replacing Non Alphanumeric Character in PHP

Wednesday, December 17, 2008

I use this when I want to change the filename uploaded by trusted user to server, it simply change non alphanumeric character (including space) into underscore.

<?php
$fileName = preg_replace ( '/[^a-zA-Z0-9]/u', '_', $fileNameStripped ); 
//code to upload the file
//...
?>
In my case, I strip the file from the extension 'cause I dont want the preg_replace to change the dot extension (ex: .jpg) into _jpg. It goes like
$fileNameStripped = 
substr($_FILES['thmbFile']['name'], 0,  strripos($_FILES['thmbFile']['name'], '.') )


Hope it helps.

Heredoc or <<<EOF in PHP

Saturday, December 6, 2008

Heredoc is a way to create string in PHP with more lines but without using quotations. Here's an example

<?php
 function some_function(){
  $content = '<a onClick="test(\'somevalue\')">Test</a>';  
  return $content;
 }
?>
can be written
<?php
 function some_function(){
  $content = <<<EOF
   <a onClick="test('somevalue')">Test</a>
  EOF;
  return $content;
 }
?>
Notice that using the heredoc we don't have to escape the quote('), that also apply to double quotes("). The following example also does the same thing.
<?php
 function some_function(){
  return <<<EOF
   <a onClick="test('somevalue')">Test</a>
  EOF;
 }
?>
The EOF itself can be replace by any string you want. Using a string like YHRGT is a good idea to make sure that string won't appear in your content.