减少从数据库中检索的字符串长度

I am fetching rows with title & its description from MySQL database. I want to alter the strings that I got from the database.

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

So please tell me, how to apply javascript to this content ($row['..'])? Means, how I can access those strings in Javascript?

If the string length is more than 50 characters, I want to limit the string & add dots (...) to it.

You can do this using substr.

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

It is better to use mb_substr() than substr()

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

Source

Why do that? Html has a css for that. you can fix the width and add the "text-overflow:ellipsis".

Try this:

<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>

If you are working with non-ASCII strings and you want to manipulate those then substr() is wrong to use. Instead you should use multibyte string functions, like mb_substr() and others.

For that you must have mbstring-extension enabled for PHP. see http://php.net/manual/en/mbstring.installation.php

I would also not directly echo string for using javascript - you never know what chars could be there and then you should start to escape some chars to work properly with javascript.

Instead I would encourage you to use json_encode. This will escape properly all special and UTF8-chars. PECL's json-extension must be enabled for json_* functions. See http://php.net/manual/en/json.installation.php

Of course if you are using Zend-framework, then proper would be use 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>

why don't you try in directly php scripting insted of javascript. you can make it as below.

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

Then you can get the title in javascript as well.

$(document).ready(function(){

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

});