Replace “ ’ ” with “ ' ” in PHP

a 夏天 提交于 2019-12-23 11:21:17

问题


I'm grabbing a string from the database that could be something like String’s Title however I need to replace the with a ' so that I can pass the string to an external API. I've used just about every variation of escaped strings in str_replace() that I can think of to no avail.


回答1:


I have just tested this:

echo str_replace('’', "'", $cardnametitle);
//Outputs: String's Title

Edit: I believe that entries in your database have been htmlentitiesed.

Note: I'm pretty sure this is not a good solution, even though it did solve your problem I think there should be a better way to do it.




回答2:


$stdin = mb_str_replace('’', '\'', $stdin);

Implementation of mb_str_replace() here: http://www.php.net/manual/en/ref.mbstring.php#107631

I mean this:

<?php
function mb_str_replace($needle, $replacement, $haystack) {
   return implode($replacement, mb_split($needle, $haystack));
}
echo mb_str_replace('’', "'", "String’s Title");

It may solve encoding problems.




回答3:


Try this

$s = "String’s Title";
$h = str_replace("’","'",$s);
echo $h;

Also can Try with preg_replace

echo preg_replace('/\’/',"'","String’s Title");



回答4:


I don't know why str_replace() is not working for you.

I feel you haven't tried it in correct way.

Refer LIVE DEMO

<?php
    $str = "String’s Title";
    echo str_replace('’', '\'', $str) . "\n";
    echo str_replace("’", "'", $str);
?>

OUTPUT:

String's Title
String's Title

UPDATE 1:

You may need to try setting the header as

header('Content-Type: text/html; charset=utf-8');



回答5:


I came across a similar issue trying to replace apostrophes with underscores... I ended up having to write this (and this was for a WordPress site):

$replace = array(",","'","’"," ","&#8217;","&#8211;");
$downloadTitle = str_replace( $replace,"_",get_the_title($gallery_id));

I'm new to PHP myself, and realize this is pretty hideous code, but it worked for me. I realized it was the "’" that REALLY needed to be factored in for some reason.



来源:https://stackoverflow.com/questions/11350466/replace-with-in-php

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!