簡體   English   中英

5個字符后的PHP替換文本?

[英]php after 5 characters replace text?

我有一堆文字

可以說

Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy.

我想這樣做,以便如果單詞長於5個字符,它將用+替換字符。 這樣那串就變成了

Lorem Ipsum is simpl+ dummy text of the print+++ and types++++++ indus+++. Lorem Ipsum has been the indus+++++ stand+++ dummy.

但是我不想包含諸如的標點符號! 和,和。 但我確實想添加撇號'

知道我該怎么做嗎?

嘗試這個:

$text = "Lorem Ipsum is simply dummy text of the printing and typesetting 
         industry. Lorem Ipsum has been the industry's standard dummy.";
echo preg_replace("/(?<=[\w']{5})[\w']/", '+', $text);

將輸出:

Lorem Ipsum is simpl+ dummy text of the print+++ and types++++++
             indus+++. Lorem Ipsum has been the indus+++++ stand+++ dummy.

使用preg_replace_callback()

function callback($matches) {
    return $matches[1] . str_repeat('+', strlen($matches[2]));
}
$str = "Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy.";
$str = preg_replace_callback("#([a-z']{5})([a-z']+)#i", 'callback', $str);
echo $str;

您可以為此使用preg_replace

$str =  "Lorem Ipsum is simply dummy text of the printing and 
         typesetting industry. Lorem Ipsum has been the industry's
         standard dummy.";

$pattern = "/([a-zA-Z]{5})([a-zA-Z]+)/";
$newStr = preg_replace($pattern,"$1+",$str);

echo $newStr;
// the + added

你必須測試一下,因為我在這台機器上沒有php

我們也可以使用strtr()

preg_match_all('/[\w\']{5}[\w\']+/', $s, $matches);
$dict = array();
foreach($matches[0] as $m){
    $dict[$m] = substr($m, 0, 5).str_repeat('+', strlen($m) - 5);
}
$s = strtr($s, $dict);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM