在php中格式化Word

时间:2016-06-21 05:44:24

标签: php mysql css

我已从php中的mysql数据库中检索值,值为paragraph。我想格式化(BOLD)' From'之后出现的单词。和' To' 例如:如果我从db获得 - 更改名字:从abc到xyz。 在这里,我想格式化(粗体)' abc'和' xyz'

编辑:

Op想要定义一个关键字列表。

他想在字符串中搜索这些关键字,并在关键字后面的单词中添加标记。

$keywords = array('From','To');
$string = 'Going From abc To xyz';
$newString = askedFunction($string, $keywords); 
// add the asked funtionality in this place
// expected result:
echo $newString; // From <b>abc</b> To <b>xyz</b>

2 个答案:

答案 0 :(得分:1)

如果您的数据与样本中的数据类似,则可以执行以下操作:

$marker = array('to', 'from', 'To', 'From');
$text = "first name changed: From abc To xyz";

$words = explode(' ', $text);
$wordsMarkup = array();
$nextBold = false;
foreach ($words as $word) {
    $wordsMarkup[] = ($nextBold === true) ? '<b>' . $word . '</b>' : $word;
    $nextBold = false;
    if(in_array($word, $marker)){
        $nextBold = true;
    }
}
echo implode(' ', $wordsMarkup);
exit;

在将单词与包含&#34;标记&#34;的数组进行比较之前,您可以添加一些正则表达式来删除非字母字符。此代码段也区分大小写。

答案 1 :(得分:0)

你可以试试这个:

$fullString = ' From abc To xyz';
$betweenFromAndTo = $this->getStringBetweenTwoStrings($fullString, 'From', 'To');
$afterTo = explode('To', $fullString)[1];
echo "From <b>$betweenFromAndTo</b> To <b>$afterTo</b>";


function getStringBetweenTwoStrings($string, $fistString, $secondString)
    {
        $stringAfterTheFirstString = explode($fistString, $string);
        if (isset($stringAfterTheFirstString[1])) {
            $stringAfterTheSecondString = explode($secondString, $stringAfterTheFirstString[1]);
            return $stringAfterTheSecondString[0];
        }
        return '';
    }