如何剪切字词并添加" ..."达到4或5个字后?
下面的代码说明我使用了基于字符的单词cutb,但我现在需要它来逐字逐句。
目前我有这样的代码:
var React = require('react');
var Link = require('react-router').Link;
var connect = require('react-redux').connect;
var Layout = React.createClass({
_handleClick: function() {
alert();
},
render: function() {
var custom = this.props.custom;
return (
<html>
<head>
<title>{custom.title}</title>
<link rel='stylesheet' href='/style.css' />
</head>
<body>
<h1>{custom.title}</h1>
<p>Isn't server-side rendering remarkable?</p>
<button onClick={this._handleClick}>Click Me</button>
{this.props.children}
<ul>
<li>
<Link to='/'>Home</Link>
</li>
<li>
<Link to='/about'>About</Link>
</li>
</ul>
<script dangerouslySetInnerHTML={{
__html: 'window.PROPS=' + JSON.stringify(custom)
}} />
<script src='/bundle.js' />
</body>
</html>
);
}
});
var wrapper = connect(
function(state) {
return { custom: state };
}
);
module.exports = wrapper(Layout);
这是title的输出:
if(strlen($post->post_title) > 35 )
{
$titlep = substr($post->post_title, 0, 35).'...';
}
else
{
$titlep = $post->post_title;
}
答案 0 :(得分:1)
变体#1
function crop_str_word($text, $max_words = 50, $sep = ' ')
{
$words = split($sep, $text);
if ( count($words) > $max_words )
{
$text = join($sep, array_slice($words, 0, $max_words));
$text .=' ...';
}
return $text;
}
变体#2
function crop_str_word($text, $max_words, $append = ' …')
{
$max_words = $max_words+1;
$words = explode(' ', $text, $max_words);
array_pop($words);
$text = implode(' ', $words) . $append;
return $text;
}
变体#3
function crop_str_word($text, $max_words)
{
$words = explode(' ',$text);
if(count($words) > $max_words && $max_words > 0)
{
$text = implode(' ',array_slice($words, 0, $max_words)).'...';
}
return $text;
}
答案 1 :(得分:1)
通常,我会爆炸身体并拉出前x个字符。
$split = explode(' ', $string);
$new = array_slice ( $split, 0 ,5);
$newstring = implode( ' ', $new) . '...';
要知道,这种方法很慢。
答案 2 :(得分:0)
您应该使用PHP的 str_replace 功能。
str_replace('your word', '...', $variable);
答案 3 :(得分:0)
在WordPress中,此功能由 .inline-header {
display: inline-block;
vertical-align: top;
}
函数完成。
wp_trim_words()
如果使用PHP执行此功能,则编写如下代码:
<?php
if(strlen($post->post_title) > 35 )
{
$titlep = wp_trim_words( $post->post_title, 35, '...' );
}
else
{
$titlep = $post->post_title;
}
?>