[英]How to get specific number of characters after a string from a string in php
[英]specific number of characters string in php
我想生成特定的字符串。 我需要為使用此功能生成確切的35個字符的字符串。
var_dump(str_pad("some text some text", 35, " ", STR_PAD_RIGHT));
因此,它給了我以下輸出:
string(35) "some text some text "
很好 它將為其余字符添加空格。
但是,對於這種情況,我想丟棄35以上的字符。
var_dump(str_pad("some text some text some text some text some text some text some text some text", 35, " ", STR_PAD_RIGHT));
電流輸出:
string(79) "some text some text some text some text some text some text some text some text"
我還需要通過丟棄字符串中的最后幾個字符來使用35個字符。
嘗試在初始字符串上使用substr
將其縮減為35個字符, 然后填充:
$data = "some text some text some text some text some text some text some text some text";
$data35 = str_pad(substr($data, 0, 35), 35, ' ', STR_PAD_RIGHT);
var_dump($data35);
/*
will output:
string(35) "some text some text some text some "
*/
if (mb_strlen($string,"UTF-8") > 34){
//there are 35 or more characters to the string
$string = mb_substr($string,0,35,"UTF-8");
}
else {
//there are 34 or less characters so carry on
$string = str_pad($string, 35, " ", STR_PAD_RIGHT));
}
使用mb_substr
刪除超過35個字符限制的字符串長度。 我認為應該建議使用這種多字節變體進行計數。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.