查看: 1204|回复: 0

PHP manual

[复制链接]
kernel 发表于 2008-10-31 09:32:30 | 显示全部楼层 |阅读模式
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;
}

?>
游客
请先登录
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

快速回复 返回顶部 返回列表