[英]Cutting a string in PHP
我有一個字符串。 有時長度超過50個字符,有時更短。 如果更長,我希望將其剪切到50個字符(或盡可能在50個字符后最接近的'。')。
我目前使用strlen
進行檢查,然后使用字符串數組將每個字符復制到新字符串中,直到達到50(在for循環中)。 這似乎是一個不好的方法,而且很慢。 我無能為力。 到目前為止
嘗試這樣的事情:
<?php
//somehow your $text string is set
if(strlen($text) > 50) {
//this finds the position of the first period after 50 characters
$period = strpos($text, '.', 50);
//this gets the characters 0 to the period and stores it in $teaser
$teaser = substr($text, 0, $period);
}
感謝@Michael_Rose,讓我們對其進行更新以獲取更安全的代碼
<?php
//somehow your $text string is set
$teaser = $text;
if(mb_strlen($text) > 50) {
//this finds the position of the first period after 50 characters
$period = strpos($text, '.', 50);
//this finds the position of the first space after 50 characters
//we can use this for a clean break if a '.' isn't found.
$space = strpos($text, ' ', 50);
if($period !== false) {
//this gets the characters 0 to the period and stores it in $teaser
$teaser = substr($text, 0, $period);
} elseif($space !== false) {
//this gets the characters 0 to the next space
$teaser = substr($text, 0, $space);
} else {
//and if all else fails, just break it poorly
$teaser = substr($text, 0, 50);
}
}
首先使用strpos
查找“。” 在前50個字符之后(例如@ohmusama說過),但一定要檢查返回值並使用mb_strlen
!
$teaser = $text;
if (mb_strlen($text) > 50) {
$period = strpos($text, '.', 50);
if ($period !== false) {
$teaser = substr($text, 0, $period);
} else {
// try finding a space...
$space = strpos($text, ' ', 50);
if ($space !== false) {
$teaser = substr($text, 0, $space);
} else {
$teaser = substr($text, 0, 50);
}
}
}
您需要做的是從字符串中獲取“子字符串”。
在PHP中,功能在這里
例如。 獲得前5個字符
echo substr('abcdef', 0, 5); //returns "abcde"
剩下的邏輯(最接近的“。”)我留給您。
這樣的事情應該起作用:
$string = substr($string, 0,
min(strpos($string, '.') >= 0? strpos($string, '.') : 50, 50));
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.