Yet another deep replace function:
<?php
function str_replace_deep( $search, $replace, $subject)
{
$subject = str_replace( $search, $replace, $subject);
foreach ($subject as &$value)
is_array( $value) and $value =str_replace_deep( $search, $replace, $value);
return $subject;
}
?>
http://cn.php.net/manual/en/function.implode.php
Many of the functions below can be simplified using this short function:
<?php
function array_implode($arrays, &$target = array()) {
foreach ($arrays as $item) {
if (is_array($item)) {
array_implode($item, $target);
} else {
$target[] = $item;
}
}
return $target;
}
$a = array('a', 'b', array('c', 'd', array('e'), 'f'), 'g', array('h'));
echo join(' - ', array_implode($a));
?>
The outputs:
<?php
a - b - c - d - e - f - g - h
?>
webmaster at tubo-world dot de
16-Jul-2008 10:47
Refering to the previous post, here an optimized version:
<?php
function implode_wrapped($before, $after, $glue, $array){
$output = '';
foreach($array as $item){
$output .= $before . $item . $after . $glue;
}
return substr($output, 0, -strlen($glue));
}
?>
mr dot bloar at gmail dot com
27-May-2008 10:12
A usefull version of implode() when you need to surround values, for example when you are working with nodes (HTML, XML)
<?php
function myImplode($before, $after, $glue, $array){
$nbItem = count($array);
$i = 1;
foreach($array as $item){
if($i < $nbItem){
$output .= "$before$item$after$glue";
}else $output .= "$before$item$after";
$i++;
}
return $output;
}
$an_array = array('value1','value2');
print myImplode("<a href=\"#\">","</a>"," > ", $an_array);
?>
output : <a href="#">value1</a> > <a href="#">value2</a>
http://cn.php.net/manual/en/function.nl2br.php
<?php
/**
* Convert BR tags to nl
*
* @param string The string to convert
* @return string The converted string
*/
function br2nl($string)
{
return preg_replace('/\<br(\s*)?\/?\>/i', "\n", $string);
}
?>
I wrote this because I wanted users to be able to do basic layout formatting by hitting enter in a textbox but still wanted to allow HTML elements (tables, lists, etc). The problem was in order for the output to be correct with nl2br the HTML had to be "scrunched" up so newlines wouldn't be converted; the following function solved my problem so I figured I'd share.
<?php
function nl2br_skip_html($string)
{
// remove any carriage returns (mysql)
$string = str_replace("\r", '', $string);
// replace any newlines that aren't preceded by a > with a <br />
$string = preg_replace('/(?<!>)\n/', "<br />\n", $string);
return $string;
}
?> |