用空格和逗号分隔字符串,然后在php的新行中打印


split the strings with space and comma and print this in a new line in php

如果字符串长度大于33,我需要在php中根据逗号和空格分割字符串。

我的代码是下面写入到一个文本文件

$Address="Kuruva Islands,Mananthavady Kodanad"; 
fwrite($fo, str_repeat(" ",(33-strlen($Address))/2).$Address."'r'n");

输出如下:

Palvelicham,
Mananthavady Kodanad

但是我需要输出中心对齐,

             Palvelicham,Mananthavady
                     Kodanad

,我也需要把它写在一个文本文件。请帮助。

为什么要用正则表达式呢?让它变得不必要的复杂?

$address="Palvelicham,Mananthavady Kodanad";
$replaced = str_replace(" ", "'n", $address);
输出:

Palvelicham,Mananthavady
Kodanad

试试这个。还没有测试,但应该可以。

$str = 'Palvelicham,Mananthavady Kodanad';
$formated_str = implode(''r'n', explode(' ', $str));

使用此函数指定字符串长度,并在空格和逗号之后使用explosion分隔。

function limit_text($text, $length) // Limit Text
{
    if(strlen($text) > $length) {
    $stringCut = substr($text, 0, $length);
    $text = substr($stringCut, 0, strrpos($stringCut, ' '));
    }
    return $text;
}

爆炸语法:

<?php
$str = "Hello world. It's a beautiful day.";
print_r (explode(" ",$str));
?>

使用strlen()和str_replace()函数,如下所示:

$str = "Kuruva Islands,Mananthavady Kodanad";
if(strlen($str) > 33) { // If the string length is greater than 33
    $str = str_replace(" ", "'n", $str); // Replace the spaces by a new line.
}
        $result="";
        $stringinput = "Palvelicham,Mananthavady Kodanad";
        $arraystring = explode(" ", $stringinput);
        $arraystringcomma = new Array();
        foreach($arraystring as $item){
            $arraystringcomma = array_merge(arraystringcomma , explode(",", $stringinput));
        }
        $stringoutput = new Array();
        $i= 0;
        foreach($arraystringcomma as $item){
            if(strlen($stringoutput[$i] . $item)<=33){
                $stringoutput[$i] .= $item;
            }else{
                $i++;
                $stringoutput[$i] = $item;
            }
        }
        $result = implode("'n",$stringoutput);