2013-09-21 61 views
0

我正在从MySQL数据库中读取标题为&的行。 我想改变从数据库中获得的字符串。减少从数据库中检索的字符串长度

<div class="title"><?php $row['title']?></div> 
<div class="details"><?php $row['desc']?></div> 

所以,请告诉我,如何应用JavaScript来此内容($行[ '..'])?意思是,我如何在JavaScript中访问这些字符串?

如果字符串长度超过50个字符,我想限制字符串&添加点(...)。

+0

'substr'是可能的在PHP那么为什么javasctipt –

+0

是的,我明白了。谢谢你的方式。 – Akshay

+0

我敢打赌,如果你搜索“阅读更多链接”片段,你会得到更高级的解决方案,不仅仅是在位置上切断你的字符串,你不会真的想......(例如,在一个词的中间,或者如果包含HTML,则销毁html) – djot

回答

0

您可以使用substr来做到这一点。

<?php echo (strlen($row['desc']) > 50) ? substr ($row['desc'] , 0, 50).'...' : $row['desc']; ?> 
+0

仅在大于50时才附加'...'。 –

+1

这是一个简短的答案,谢谢你..这两个urs和阿马尔的答案是相同的只是格式改变..所以,你们都谢谢。 – Akshay

1

这是更好地使用mb_substr()substr()

<?php 
echo mb_substr($row['title'],0,50); 

Source

0

为什么这样做? Html有一个CSS。你可以修改宽度并添加“text-overflow:ellipsis”。

试试这个:

<div class="fixedWidth title"><?php $row['title']?></div> 
<div class="fixedWidth details"><?php $row['desc']?></div> 

<style> 
    .fixedWidth{ 
     width:200px; 
     white-space: nowrap; 
     overflow: hidden; 
     text-overflow:ellipsis; 
    } 
</style> 
0

如果您正在使用非ASCII字符串并要处理那些然后SUBSTR()是错误的使用。相反,您应该使用多字节字符串函数,如mb_substr()others

为此,您必须为PHP启用mbstring-extension。看到http://php.net/manual/en/mbstring.installation.php

我也不会直接回声字符串使用JavaScript - 你永远不会知道什么字符可以在那里,然后你应该开始转义一些字符与JavaScript正常工作。我会鼓励你使用json_encode。这将正确地逃脱所有特殊和UTF8字符。 必须为json_ *函数启用PECL的json扩展。见http://php.net/manual/en/json.installation.php

当然,如果你使用的是Zend -framework,然后适当将使用Zend_Json::encode()

<?php 
    $maxLength = 50; 
    $encoding = 'UTF-8'; 
    $tail = ' ...'; 
    $row['desc'] = (mb_strlen($row['desc'], $encoding) > $maxLength) ? mb_substr($row['desc'], 0, $maxLength, $encoding) . $tail : $row['desc']; 

?> 
<script type="text/javascript"> 
    var rowData = <?php echo json_encode($row); ?>; 
    alert(rowData.desc); 
</script> 
0

你为什么不尝试直接PHP脚本insted的JavaScript代码。 你可以如下。

<div class="title"><?php echo $title = strlen($row['title']) > 50 ? substr($row['title'], 0, 50)."..." : $row['title']; ?></div> 

然后你可以在javascript中获得标题。

$(document).ready(function(){ 

var title = $(".title").text(); 

}); 
+0

如果您将代码使用代码按钮,将在行的开始处创建4个空格。 – jcubic