How to truncate string before POST?

42 views Asked by At

I'm currently trying to teach myself PHP, so forgive my lack of understanding.

I am trying to post two strings to my database. The first string (div1) can be long, and the second string (title) should be a truncated version of the first, such as 15 characters, used as a title.

Through searching the internet, I've found a function to help me, but I'm struggling to implement it. I have tried to cobble together two functions, but I don't know how. The post does work. It can send the div1, but when trying to add the truncate function, it stops working.

This is the post action file (saveNewText.php). The include 'header.php' has a require for the functions.php file.

<?php include 'header.php' ?>

<?php

    // remove these 3 lines, and it'll work again
    $original_string = $newText;
    $max_chars = 15;
    $newTitle = truncate_string_at_word($original_string, $max_chars);

    // this part works when the above 3 lines are not included, except it's not posting a title yet
    $newText = $_POST['newText'];
    if ($newText != ""){
        $sql = "UPDATE notetable SET div1 = '".$newText."', title = '".$newTitle."' WHERE id=1 "; // how to truncate the title?
        $result = mysqli_query($conn,$sql);
    }

?>

This is the function from the functions file (functions.php).

<?php

function truncate_string_at_word($string, $max_chars)
{
  $string = trim($string);
  if (strlen($string) > $max_chars) {
    $string = substr($string, 0, $max_chars);
    $pos = strrpos($string, " ");
    if ($pos === false) {
      return $string;
    }
    return substr($string, 0, $pos);
  } else {
    return $string;
  }
} 

?>
0

There are 0 answers