【问题标题】:How to get the first paragraph bold in the php?如何在php中使第一段加粗?
【发布时间】:2014-06-18 02:21:46
【问题描述】:

我在数据库中分两段输入文本

first paragraph
second paragraph

我将它们存储在我的数据库中,当我使用nl2br 在前端显示它们时,它会完美显示。

我希望我的第一段是粗体,第二段应该是正常的。

我尝试使用strposnl2br 之后找到<br> 标记的位置以删除第一段,但我没有成功。

失败的代码是

echo strpos(nl2br($row['article']), "<br>");

但我没有得到&lt;br&gt; 标签的位置

我从 eddie 那里得到了正确答案,他删除了它,但我在这里更新答案

$str='first paragraph
      second paragraph';
foreach(explode("\n",) as $key => $val) { 
if($key == 0){
echo'<b>'; 
}     
echo $val;
echo'<br>';
if($key == 0){ 
echo '</b>';
}
}

【问题讨论】:

  • 有代码,会出差。
  • 那么你的代码在哪里?即使是失败的尝试?
  • 为什么不直接使用 CSS?
  • &lt;p&gt;&lt;b&gt;first paragraph&lt;/b&gt;&lt;/p&gt;&lt;p&gt;second paragraph&lt;/p&gt;那里
  • 所以?您仍然可以使用 CSS 选择器仅定位第一段。

标签: php nl2br


【解决方案1】:

不要将nl2br 用于您要查找的结果类型。只需使用带有preg_split 的正则表达式规则将字符串拆分为一个数组,然后对数组中的第一项进行操作。这是测试代码:

// Set the test data.
$test_data = <<<EOT
first paragraph
second paragraph
EOT;

// Split the test data into an array of lines.
$line_array = preg_split('/(\r?\n){1,2}/', $test_data);

// Roll through the line array & act on the first line.
$final_text = '';
foreach ($line_array as $line_key => $line_value) {
  if ($line_key == 0) {
    $line_value = "<b>" . $line_value . "</b>";
  }
  $final_text .= $line_value . "<br />\n";
}

// Dump the line array for debugging.
echo '<pre>';
print_r($line_array);
echo '</pre>';

// Echo the final text.
echo '<pre>';
echo htmlentities($final_text);
echo '</pre>';

die();

线阵列转储的输出是这样的:

Array
(
    [0] => first paragraph
    [1] => second paragraph
)

测试输出使用htmlentities 来显示 HTML 方面做了什么:

<b>first paragraph</b><br />
second paragraph<br />

【讨论】:

    【解决方案2】:

    试试:

    $first_line = explode(PHP_EOL, $str)[0];
    $new_str = str_replace($first_line,'<b>'.$first_line.'</b>',nl2br($str));
    

    【讨论】:

      猜你喜欢
      • 2016-11-04
      • 1970-01-01
      • 2013-01-19
      • 1970-01-01
      • 2017-05-24
      • 2014-10-02
      • 2014-07-08
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多