search
HomeBackend DevelopmentPHP Tutorialjavascript - PHP正则替换问题

js下正则是这样的:

<code>var str = "data\/ui_inner\/74\/";
str.replace(/\\/,"");
</code>

php如下这样写却不对:

<code>$auto_url = preg_replace('/\\/','', $str);
</code>

我的目的是替换字符串中的\为空,请问如何替换呢?

按照楼下的答案试了试还是不行呢。。
javascript - PHP正则替换问题

找到原因了,是因为json_encode()导致的,请问如何解决呢?我去google一下

回复内容:

js下正则是这样的:

<code>var str = "data\/ui_inner\/74\/";
str.replace(/\\/,"");
</code>

php如下这样写却不对:

<code>$auto_url = preg_replace('/\\/','', $str);
</code>

我的目的是替换字符串中的\为空,请问如何替换呢?

按照楼下的答案试了试还是不行呢。。
javascript - PHP正则替换问题

找到原因了,是因为json_encode()导致的,请问如何解决呢?我去google一下

javascript - PHP正则替换问题


除非楼主有洁癖, 否则不建议再去对 json_encode 的结果进行替换, 因为 json_encode/ 进行转义输出, 对于js来说, 它的内容 还是 /, 而不是 \/.

javascript - PHP正则替换问题

(PS:下面在测试的时候有注释代码里的var_dump, 只保留echo)
替换的:
javascript - PHP正则替换问题

不替换的:
javascript - PHP正则替换问题

1.html 的代码如下:

<script type="text/javascript" src="jquery.min.js"></script>
<script type="text/javascript">
$.ajax({
    type: "get",
    url: "f.php",
    dataType: "json",
    success: function(data) {
        console.log(data.url);
    }
});
</script>

PHP中提供了一个函数 preg_quote

<code>string preg_quote ( string $str [, string $delimiter = NULL ] )
</code>

preg_quote()需要参数 str 并向其中 每个正则表达式语法中的字符前增加一个反斜线。 这通常用于你有一些运行时字符串 需要作为正则表达式进行匹配的时候。

正则表达式特殊字符有: . \ + * ? [ ^ ] $ ( ) { } = ! | : -

<code><?php $keywords = '$40 for a g3/400';
$keywords = preg_quote($keywords, '/');
echo $keywords; // 返回 \$40 for a g3\/400
</code></code>

所以以上代码可以这样写

<code><?php $str = "data\/ui_inner\/74\/";
$pattern = preg_quote('\\');
$auto_url = preg_replace('/'.$pattern.'/','', $str);
echo $auto_url;</code></code>

应该这么写

<code>$auto_url = preg_replace('/\\\\/','', $str);</code>

也是刚学到,因为在字符串中,'\'也是转义,'/\\/'就变成了'/\/',所以要四个。
也可以用str_replace

<code>$auto_url = str_replace('\\','', $str);</code>

PHP的单引号中仍然会转义\
所以你需要这么做

$auto_url = preg_replace('/\\\\/', '', "data\/ui_inner\/74\/");

改成四个\\\\

直接对json做正则替换是不安全的,因为如果业务逻辑有改变,你可能意外修改了其他的域,建议先decode之后修改好之后再重新encode

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
PHP Dependency Injection Container: A Quick StartPHP Dependency Injection Container: A Quick StartMay 13, 2025 am 12:11 AM

APHPDependencyInjectionContainerisatoolthatmanagesclassdependencies,enhancingcodemodularity,testability,andmaintainability.Itactsasacentralhubforcreatingandinjectingdependencies,thusreducingtightcouplingandeasingunittesting.

Dependency Injection vs. Service Locator in PHPDependency Injection vs. Service Locator in PHPMay 13, 2025 am 12:10 AM

Select DependencyInjection (DI) for large applications, ServiceLocator is suitable for small projects or prototypes. 1) DI improves the testability and modularity of the code through constructor injection. 2) ServiceLocator obtains services through center registration, which is convenient but may lead to an increase in code coupling.

PHP performance optimization strategies.PHP performance optimization strategies.May 13, 2025 am 12:06 AM

PHPapplicationscanbeoptimizedforspeedandefficiencyby:1)enablingopcacheinphp.ini,2)usingpreparedstatementswithPDOfordatabasequeries,3)replacingloopswitharray_filterandarray_mapfordataprocessing,4)configuringNginxasareverseproxy,5)implementingcachingwi

PHP Email Validation: Ensuring Emails Are Sent CorrectlyPHP Email Validation: Ensuring Emails Are Sent CorrectlyMay 13, 2025 am 12:06 AM

PHPemailvalidationinvolvesthreesteps:1)Formatvalidationusingregularexpressionstochecktheemailformat;2)DNSvalidationtoensurethedomainhasavalidMXrecord;3)SMTPvalidation,themostthoroughmethod,whichchecksifthemailboxexistsbyconnectingtotheSMTPserver.Impl

How to make PHP applications fasterHow to make PHP applications fasterMay 12, 2025 am 12:12 AM

TomakePHPapplicationsfaster,followthesesteps:1)UseOpcodeCachinglikeOPcachetostoreprecompiledscriptbytecode.2)MinimizeDatabaseQueriesbyusingquerycachingandefficientindexing.3)LeveragePHP7 Featuresforbettercodeefficiency.4)ImplementCachingStrategiessuc

PHP Performance Optimization Checklist: Improve Speed NowPHP Performance Optimization Checklist: Improve Speed NowMay 12, 2025 am 12:07 AM

ToimprovePHPapplicationspeed,followthesesteps:1)EnableopcodecachingwithAPCutoreducescriptexecutiontime.2)ImplementdatabasequerycachingusingPDOtominimizedatabasehits.3)UseHTTP/2tomultiplexrequestsandreduceconnectionoverhead.4)Limitsessionusagebyclosin

PHP Dependency Injection: Improve Code TestabilityPHP Dependency Injection: Improve Code TestabilityMay 12, 2025 am 12:03 AM

Dependency injection (DI) significantly improves the testability of PHP code by explicitly transitive dependencies. 1) DI decoupling classes and specific implementations make testing and maintenance more flexible. 2) Among the three types, the constructor injects explicit expression dependencies to keep the state consistent. 3) Use DI containers to manage complex dependencies to improve code quality and development efficiency.

PHP Performance Optimization: Database Query OptimizationPHP Performance Optimization: Database Query OptimizationMay 12, 2025 am 12:02 AM

DatabasequeryoptimizationinPHPinvolvesseveralstrategiestoenhanceperformance.1)Selectonlynecessarycolumnstoreducedatatransfer.2)Useindexingtospeedupdataretrieval.3)Implementquerycachingtostoreresultsoffrequentqueries.4)Utilizepreparedstatementsforeffi

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),