php 内的 substr echo

substr inside php echo

在我下面的代码中 substr 函数不起作用,为什么会这样以及如何让它起作用。

<?php
// some code

echo "
<h2>".$row['title']."</h2>
<p> substr( ".$row['body'].",0,300) ....</p>
<p>".$row['posted']."</p>";

正确的代码应该是这样的:

echo "
<h2>". $row['title'] ."</h2>
<p> ". substr($row['body'],0,300) ." ....</p>
<p>". $row['posted'] ."</p>";

Because substr($row['body'],0,300) is php syntax you you need to separate it.

echo "
<h2>".$row['title']."</h2>
<p>" . substr($row['body'],0,300) . " ....</p>
<p>".$row['posted']."</p>";

你没有正确格式化它,substr 不能在引号内。

In my code below substr function is not working, why it is so?

  • 这是因为它被视为字符串文字而不是函数

How to make it work?

  • 您需要注意字符串连接或简单地将 substr 的值存储在一个变量中。

示例:

$substr_value = substr($row['body'],0,300);
echo "
<h2>{$row['title']}</h2>
<p>$substr_value</p>
<p>{$row['posted']}</p>";