Aidan's PHP Repository

A repository for PHP functions and classes ...

function.str_encase.php

Prefix and/or affix every line, in a block of text.

  • Author: Aidan Lister <aidan@php.net>
  • Version: 1.1.0
  • Link: http://aidanlister.com/repos/v/function.str_encase.php
  • Views: 5047
  • Downloads: 1004

Source

Download this script <?php
/**
 * Prefix and/or affix every line, in a block of text.
 *
 * @author      Aidan Lister <aidan@php.net>
 * @version     1.1.0
 * @link        http://aidanlister.com/repos/v/function.str_encase.php
 * @param       string    $text     Text
 * @param       string    $prefix   Prefix string
 * @param       string    $affix    Affix string
 */
function str_encase($text, $prefix = '', $affix = '')
{
    // Handle line endings correctly
    $str = preg_replace('#(\r\n?|\n)#s', $affix . '\1' . $prefix, $text);
 
    // Finish string
    return $prefix . $str . $affix; 
}
 
?>

Example

<pre>
<?php
require_once 'function.str_encase.php';
 
echo "pc lineendings\n";
$pc = "item1\r\nitem2\r\nitem3";
echo str_encase($pc, '* '), "\n\n";
 
echo "unix lineendings\n";
$unix = "item1\nitem2\nitem3";
echo str_encase($unix, '[html]', '[/html]'), "\n\n";
 
echo "mac lineendings\n";
$mac = "item1\ritem2\ritem3";
echo str_encase($mac, null, ' sucks');
 
?>
</pre>

Output

pc lineendings
* item1
* item2
* item3

unix lineendings
[html]item1[/html]
[html]item2[/html]
[html]item3[/html]

mac lineendings
item1 sucks
item2 sucks
item3 sucks

Comments

November 2nd, 2005
I really don't see the need for the 's' modifier in the regex... you don't even use the dot, so you're only creating more load (not THAT much) for PCRE... [Editor's Note: Spot on, fixed!]