user1232551
user1232551

Reputation: 53

how to replace ' with another special character using str_replace php

I have a function that receives a post title and cut it when the post title is longer than 40 character. The function works very well except when the string has ' in it.

This is how the browser display the title in the original page (before the 'cut')

dall'high-tech all'high-car, bla bla bla bla bla bla bla bla bla bla bla

When the string is passed to the function and the function cut it at the 40-th character the string returned is very short:

dall'high-tech

I am using substr() to cut it after the 40-th character:

substr($my_string, 0, 40);

I think the problem has to do with the ' character in the string. I have tried to replace the ' character with chr(134) using

str_replace("'", chr(134), $my_string);

But str_replace() fails to replace ' with . (I tried also using \' and chr(39) instead of ' and also using B instead of chr(134)).

So, now I don't know what to do. I have spent already 5 hours trying to fix this problem. I am sure someone has gone through it before and might help me.

Thank you

Upvotes: 1

Views: 607

Answers (1)

Jeremy Harris
Jeremy Harris

Reputation: 24549

Try doing this before you do the substr():

$my_string = html_entity_decode($my_string, ENT_QUOTES);

Another option to try is using mb_substr() which performs a multi-byte safe substr() operation based on number of characters.

Upvotes: 2

Related Questions