开发者

PHP trim string to 140 chars, remove some chars and add a URL

Looking for a bunch of things really.

Essentially what I'm looking to create is the following string which can only contain MAX 140 chars (see where I'm going with this):

"Some text here from an XML feed... #tweeted http://bit.ly/123456" 

So I already have a $text variable which contains the text from the XML feed, this text string will always contain the string #tweeted and can be of any length.

Lets say thats 200 chars for this example, including the hashtag.

I know need to make room for the ...<space>开发者_高级运维 and http://bit.ly/123456 (24 Chars in total)

  1. Remove the #hashtag E.g: $removehash = str_replace("#tweeted", " ", $text);

  2. Get the length E.g. $length = strlen($text);

  3. Trim it to 116, if over 140 chars.

  4. If under 116 chars do nothing because there is space for the ... and the link

  5. add the ... and the URL ($url).

Any advice, if you've done this previously, or any ideas on how to trim the string, remove the hashtag and apend to the end of the string to contrain it to a max of 140 chars greatly appreciated.

Not sure how to trim the text?


PHP's substr function returns a portion of a string so you can, for example, get the first 116 chars of a string by

$s = substr( $s, 0, 116 );

It sounds like you are taking a 140 char string + #tweeted + URL and wanting to produce an output string of not greater than 140 chars? I would try something like:

$s = "Some text here from an XML feed that is 140 chars or less #tweeted http://bit.ly/123456";
$b = explode( "#tweeted", $s );

$txt = trim( $b[0] );
$url = trim( $b[1] );

$txt = substr( $txt, 0, 139 - strlen( $url ) );

$output = $txt . " " . $url;

Obviously I've used too many temporary variables but hopefully that makes it clearer. Would also need to validate input string if necessary or the first explode will not return the expected result. The 139 in the sub is 140 char output - 1 char for the space in the result string.

The substr line takes into account that the bitly URLs may be of different lengths and doesn't just blindly cut off at 116 chars.


Remove hashtag:

// For php 5.3 +
$removeHash = function($var){
    return (substr($var, 0, 1) != '#');
};

/*
For php 5.2 use the following
function removeHash($var){
    return (substr($var, 0, 1) != '#');
}
$removeHash = 'removeHash';
*/

$textlst = explode(" ", $text);
$removedHashText = implode(" ", array_filter($textlst, $removeHash));

Trim over 140:

if (count($text) > 140){
    $url = getUrl(); // what ever this might be
    $text = substr($text, 0, 116);
    $text .= "... $url";
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜