如何在mysql中以html格式存储数据时在php中使用substring?

时间:2017-05-23 09:46:46

标签: php html mysql substring substr

文本以HTML格式段落标记存储。

字段名称:descr

存储数据:

<html>
<head>
    <title></title>
</head>
<body>
<div class="campusInfoNamesake">
<p>If someone had said to me ten years ago that autism and the therapeutic benefits of gardening will become your life, I wouldn&rsquo;t have believed them.</p>

<p>Although it&rsquo;s still very early days, things are starting to take shape on my smallholding in Ceredigion, West Wales.</p>
</div>
</body>
</html>

上面的结构只有存储在表中的数据见下面的mysql表图像:

enter image description here

我需要在body标签中只检索100个字符串.. 我使用了以下代码: <?php echo substr($row01[descr], 100); ?> 但是在使用这段代码时我无法得到结果。 请帮帮我。

2 个答案:

答案 0 :(得分:0)

您需要先使用正则表达式检索<body> - 标签之间的所有内容,然后才能剪切所需的字符串。

preg_match_all('/<body>(.*?)<\/body>/s', $row01['desc'], $matches);

//HTML array in $matches[1]
print_r(substr($matches[1],100));

请参阅此处的正则表达式:PHP Regex find text between custom added HTML Tags

答案 1 :(得分:0)

我将把自己放在自己的位置,并就如何最好地准备这篇文章做出几个假设。如果我在这里错误的方式,请告诉我......

输入:

$row01['descr']='<html>
<head>
    <title></title>
</head>
<body>
<div class="campusInfoNamesake">
<p>If someone had said to me ten years ago that autism and the therapeutic benefits of gardening will become your life, I wouldn&rsquo;t have believed them.</p>

<p>Although it&rsquo;s still very early days, things are starting to take shape on my smallholding in Ceredigion, West Wales.</p>
</div>
</body>
</html>';

方法(preg_match pattern demo)(php demo):

$body_text=preg_match('/<body>\s\K.+(?=<\/body)/s',$row01['descr'],$out)?$out[0]:'';  // extract body text
$tagless_text=strip_tags($body_text);                     // remove tags from body text
$decoded_text=html_entity_decode($tagless_text);          // decode entities like: &rsquo;
$pattern=['/[\n\r ]+/','/^ +| +$/'];                             
$replace=[' ',''];
$compacted_text=preg_replace($pattern,$replace,$decoded_text);   // remove extra spacing
$truncated_text=substr($compacted_text,0,100);       // cut the string to max length of 100
echo $truncated_text,'...';                          // print to screen and append with ...

输出:

If someone had said to me ten years ago that autism and the therapeutic benefits of gardening will b...