1

How can I this PHP function include in jquery .html?

PHP function:

function trim_text($string, $limit, $break="<", $pad=" ...")
{
$words = explode(' ', htmlentities(strip_tags($string)));
$countr = count($words);
if ($countr <= 8)
{
return $string;
}else{


// return with no change if string is shorter than $limit
if(strlen($string) <= $limit) return $string;
$string = substr($string, 0, $limit);
if(false !== ($breakpoint = strpos($string, $break, $limit))) {
if($breakpoint < strlen($string) - 1) {

  $string = substr($string, 0, $breakpoint) . $pad;
}
}
$last_space = strrpos(substr($string, 0, $limit), ' ');
$string = substr($string, 0, $last_space);
$string = strip_tags($string);  
return $string.$pad;
}
}

And the Jquery part of code where I want to in ".html" part somehow call this function is:

$(" .text").html('<div>'+ message +'</div>');

What I want to do is trim this "message" text using PHP function. Is it possible?

1
  • You could make an ajax call passing the message as a post param to the page and having php parse it and return it back to you. Commented Apr 6, 2010 at 10:41

3 Answers 3

2

In your JS, send the text to be trimmed to the script which will do the trimming. The server should send back the trimmed string, e.g.:

var theText = $("#aTextarea").val();
$.post('trimscript.php', {text: theText}, function(response) {
    $('.text').html('<div>' + response + '</div>');
});

In your PHP, grab the GET or POST variable, trim it, and send it back:

<?php
if(isset($_POST['text']) && !empty($_POST['text'])) {
    $text = trim_text($_POST['text']);
    echo $text;
}
?>

I think that describes the flow of what's needed. Of course, there are numerous other ways to implement this, the above is merely a simple example.

Sign up to request clarification or add additional context in comments.

Comments

1

a lot of php function have been rewritten in javascript. you can find them here

1 Comment

over a year later, and this answer is helpful. Very cool site
0

It would be much better to implement this function using javascript.
If this message coming from the server, you can trim it before sending

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.