Php 如果没有空格和标点符号,则修剪空格和标点符号的函数
我正在尝试创建一个函数,该函数可以剪切字符串中的空格,并在没有空格的情况下添加标点符号 这是我的测试字符串:Php 如果没有空格和标点符号,则修剪空格和标点符号的函数,php,Php,我正在尝试创建一个函数,该函数可以剪切字符串中的空格,并在没有空格的情况下添加标点符号 这是我的测试字符串: $test = 'Hey there I am traa la la '; 我希望它变成这样: $test = 'Hey there I am traa la la.'; 以下是我尝试过的功能: function test($mytrim){ for($i = 0; $i <= 5; $i++){ if(substr(
$test = 'Hey there I am traa la la ';
我希望它变成这样:
$test = 'Hey there I am traa la la.';
以下是我尝试过的功能:
function test($mytrim){
for($i = 0; $i <= 5; $i++){
if(substr($mytrim, 0, -1) == ''){
$mytrim = substr($mytrim, 0, -1);
}
}
$punct = array(".",",","?","!");
if(!in_array($mytrim, $punct)){ $mytrim .= '.'; }
return $mytrim;
}
知道它为什么不工作吗?PHP有一个内置函数。至于标点符号,您的代码应该可以很好地添加标点符号
function test ($string)
{
$string = trim($string);
if ((substr($string, -1)) != ".")
{
$string .= ".";
}
}
代码示例:
<?php
$testString = " hello world ";
$trimmedString = trim($testString); // will contain "hello world"
$lastChar = substr($trimmedString, strlen($trimmedString)-1); // will be "d"
$punct = array(".",",","?","!");
if(!in_array($lastChar, $punct))
echo $trimmedString.'.'; //will output "hello world."
PHP有一个内置函数。至于标点符号,您的代码应该可以很好地添加标点符号
代码示例:
<?php
$testString = " hello world ";
$trimmedString = trim($testString); // will contain "hello world"
$lastChar = substr($trimmedString, strlen($trimmedString)-1); // will be "d"
$punct = array(".",",","?","!");
if(!in_array($lastChar, $punct))
echo $trimmedString.'.'; //will output "hello world."
这是行不通的-它应该只添加一个标点符号,如果还没有根据规范编辑。。。与您的代码类似,只是使用三元运算符。这不起作用-它应该只添加标点符号,如果还没有标点符号,请根据规范编辑。。。类似于只使用三元运算符的代码。
function adspunctuation($str)
{
$str = trim($str) . (substr($str, -1)!='.' ? '.' : '');
return $str;
}