Question

I am trying to replace double quotations with the word " before inserting into the database, but when trying to fetch my text from the database I cannot convert the quotes after using this function to display certain words from the whole sentence.

What I eventually want to do:

  1. Input the string Word "blabla" more text for example to the database
  2. Before putting to the database, convert the special characters like " to the correct code (&quote;)
  3. When retrieving the string from the database, it must put the code &quote; again to " to display on my page

Besides that, I also want to create a function that works like substr() but splits on full words instead of single characters.

This is my current code:

function sanitize_words($string) {
    preg_match_all("/\p{L}[\p{L}\p{Mn}\p{Pd}'\x{2019}]*/u",$string,$matches,PREG_PATTERN_ORDER);
    return $matches[0];
}
function words($text,$len) {
    $words_in_text = sanitize_words($text);
    $words_to_return = $len;
    $result = array_slice($words_in_text,0,$words_to_return);
    return implode(" ",$result);
}

However when I try to replace the "quot;" text back to normal " quotes, it doesn't show on my page.

Was it helpful?

Solution

After our discussion in chat, we managed to solve it as following:

Problem 1

Inserting html entities in the database and correctly displaying it again in html.

  1. Before inputting the string to the database, use this function to convert the special characters to the correct entity codes:

    $newstring = htmlentities( $oldstring , ENT_QUOTES, "UTF-8")

  2. Then input $newstring into your database. It will have special characters like " converted to &quote;.

  3. When retrieving the string from the database, it should automatically show the correct symbol (") in the html, without you having to do anything!

If you are still having trouble with displaying the string, then you can check html_entity_decode().

Problem 2

Creating a function that works like substr(), but works with words instead of single characters.

function subword($string, $amount){
    $explode = explode(" ", $string);
    $newstring = "";
    for($i = 0; $i < $amount; $i++){
        $newstring.= " ".$explode[$i];
    }
    return substr($newstring, 1);
};

$text = "This is a sentence with a lot of words and spaces!";
subword($text, 4);  //This will give you the first 4 words "This is a sentence"
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top