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
6 个解决方案
#1
151
$small = substr($big, 0, 100);
For String Manipulation here is a page with a lot of function that might help you in your future work.
對於字符串操作,這里有一個具有很多功能的頁面,這些功能可能對您以后的工作有所幫助。
#2
28
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...)
你可以創建一個函數,它使用這個函數並附加例如'…表示它被縮短了。(我想當這篇文章發布的時候,已經有上百個類似的回復了…)
#3
19
$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
#4
18
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);
}
#5
15
A late but useful answer, PHP has a function specifically for this purpose.
PHP有一個專門用於此目的的函數,這是一個很晚但很有用的答案。
mb_strimwidth
$string = mb_strimwidth($string, 0, 100);
$string = mb_strimwidth($string, 0, 97, '...'); //optional characters for end
#6
2
Without php internal functions:
沒有php內部函數:
function charFunction($myStr, $limit=100) {
$result = "";
for ($i=0; $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);