你如何在 PHP 中提取字符串的前 100 个字符
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/317336/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How do you pull first 100 characters of a string in PHP
提问by JoshFinnie
I am looking for a way to pull the first 100 characters from a string variable to put in another variable for printing.
我正在寻找一种从字符串变量中提取前 100 个字符以放入另一个变量进行打印的方法。
Is there a function that can do this easily?
有没有可以轻松做到这一点的功能?
For example:
例如:
$string1 = "I am looking for a way to pull the first 100 characters from a string variable to put in another variable for printing.";
$string2 = 100charfunction($string1);
print $string2
To get:
要得到:
I am looking for a way to pull the first 100 characters from a string vari
回答by Patrick Desjardins
$small = substr($big, 0, 100);
For String Manipulationhere is a page with a lot of function that might help you in your future work.
对于字符串操作,这里有一个包含很多功能的页面,可能会对您未来的工作有所帮助。
回答by Stein G. Strindhaug
You could use substr, I guess:
你可以使用 substr,我猜:
$string2 = substr($string1, 0, 100);
or mb_substr for multi-byte strings:
或 mb_substr 用于多字节字符串:
$string2 = mb_substr($string1, 0, 100);
You could create a function wich uses this function and appends for instance '...'to indicate that it was shortened. (I guess there's allready a hundred similar replies when this is posted...)
您可以创建一个使用此函数的函数并附加例如'...'以指示它已被缩短。(我猜这个贴出来的时候已经有一百个类似的回复了……)
回答by markus
$x = '1234567'; echo substr ($x, 0, 3); // outputs 123 echo substr ($x, 1, 1); // outputs 2 echo substr ($x, -2); // outputs 67 echo substr ($x, 1); // outputs 234567 echo substr ($x, -2, 1); // outputs 6
回答by Coz
A late but useful answer, PHP has a function specifically for this purpose.
一个迟到但有用的答案,PHP 有一个专门用于此目的的函数。
$string = mb_strimwidth($string, 0, 100);
$string = mb_strimwidth($string, 0, 97, '...'); //optional characters for end
回答by Kostis
try this function
试试这个功能
function summary($str, $limit=100, $strip = false) {
$str = ($strip == true)?strip_tags($str):$str;
if (strlen ($str) > $limit) {
$str = substr ($str, 0, $limit - 3);
return (substr ($str, 0, strrpos ($str, ' ')).'...');
}
return trim($str);
}
回答by joan16v
Without php internal functions:
没有php内部函数:
function charFunction($myStr, $limit=100) {
$result = "";
for ($i=0; $i<$limit; $i++) {
$result .= $myStr[$i];
}
return $result;
}
$string1 = "I am looking for a way to pull the first 100 characters from a string variable to put in another variable for printing.";
echo charFunction($string1);

