如何从字符串中删除空格(换行)?

时间:2013-09-26 09:41:23

标签: php preg-replace

我的字符串是:

$str = "[php] 

complete
once
A lot of text and other staffs!
but

[/php]";

$str = preg_replace("/\[php\]\s*(.*?)\s*\[\/php]/is","<pre>\\1</pre>",$str);

echo $str;

on out:

<pre>complete
once
A lot of text and other staffs!
but</pre>

它适用于沙箱test,但在我的网站上,我在文本的末尾有一个空格(新行):

test1 without U

有趣的是,如果我将使用“U”修饰符而不是空格(新行)将位于文本的顶部:

test2 with U

$str = preg_replace("/\[php\]\s*(.*?)\s*\[\/php]/Uis","<pre>\\1</pre>",$str);

textarea的屏幕:

in the textarea

更新这是一个非常基本的页面(示例),你可以将[php] bbcode放在表单上的textarea中并提交。

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<style>
.code {
    border: 1px solid #c2c2c2;
    padding: 4px;
    border-radius: 4px;
}
</style>
</head>
<body>
<?php 
$str = $_POST['textarea'];
$content = preg_replace("/\[php\]\s*(.*)\s*\[\/php\]/si","<pre class='code'>\\1</pre>",$str);
echo $content;
?>
<form method="post" action="" class="contactform">
<textarea name="textarea"></textarea>
<input type="submit" class="met_button pull-right" name="submit" value="Send">
</form>
</body>
</html>

你会在底部或顶部看到空格。

1 个答案:

答案 0 :(得分:0)

试试这个:

$str = "[php]       

complete
once
A lot of text and other staffs!
but


[/php]";

$arr = array('[php]','[/php]');

$string = str_replace($arr,'', $str);
echo $string ;

输出:

complete
once
A lot of text and other staffs!
but