在PHP中的每个字符串中转义单引号 [英] Escape single quotes in every string in php

查看:120
本文介绍了在PHP中的每个字符串中转义单引号的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我遇到这样的问题:

编写一个函数,该函数的参数可以是字符串数组或数组。该函数应该在找到的每个字符串中转义引号,并返回修改后的数组。

Write a function that takes an argument that can be array of strings or arrays. The function should escape quotes in every string it find and return the modified array.

现在我的解决方法是:

function string(arr){

      foreach ($arr as $key => $value) {
        $newValue = str_replace(" ", '', $arr[$key]);
        return $arr; 
      }  
 }

我的问题是我做的对吗?我的解决方案对吗?我理解正确吗?根据我的理解,我应该将字符串中所有的单引号替换为onyl。任何建议,不胜感激。非常感谢

My questions is am I doing right? Is my solution is right also? Am I understanding it correctly? Based on my understanding, I should replace onyl all the single quotes find in the string. Any suggestions is much appreciated. Thank you very much

推荐答案

嗯...不,您的走法不是正确的。

Well...no, you're not really on the right track.

这是我的建议。

如果您使用的是PHP 5.3 +:

If you're using PHP 5.3+:

function escapeQuotes(array $array)
{
     $return_array = [];
     array_walk_recursive($array, function($x) use (&$return_array)
     {
         $return_array[] = str_replace("'", "\\'", $x); 
         // note that this will escape the single quote not replace it. 
         // Not sure on the \\ behaviour though.
         // Things may get weird when returned
     }
     return $return_array;

}

这篇关于在PHP中的每个字符串中转义单引号的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆