如何删除一个字符串的特定部分的JavaScript文件 [英] How to remove a particular part of a string in a JavaScript file

查看:71
本文介绍了如何删除一个字符串的特定部分的JavaScript文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用PHP,我希望能够打开一个JavaScript文件,并采取了一个特定的行的一部分。使用下面的例子中,我会想从文件中删除8:20 am|8:20am,保持一切完好无损。

Using PHP, I want to be able to open a JavaScript file and take out a part of a particular line. Using the example below, I would want to remove "8:20am|8:20am" from the file, keeping everything else intact.

我的JavaScript文件看起来是这样的:

My JavaScript file looks like this:

var daylist = document.checkout.checkoutDay
var timelist = document.checkout.times
var times = new Array()
times[1]=["8:00am|8:00am", "8:20am|8:20am", "8:40am|8:40am", "9:00am|9:00am"]

有可能是在阵列中的多个线路和每个不同的时代,所以我不会确切地知道在哪里可以找到字符串。我想也许用str_replace()函数和fopen()函数打开文件,但不知道是什么行会看起来像提前,我不知道,以替换字符串。任何想法?

There may be multiple lines in the Array and each with different times, so I won't know exactly where to find the string. I was thinking of maybe using str_replace() and fopen() to open the file, but without knowing what the line is going to look like ahead of time, I wouldn't know what string to replace. Any ideas?

推荐答案

如果你想的只能更换这个特定行的次数的您可能需要使用 preg_replace()此:

If you want to only replace the occurance on this specific line you may want to use preg_replace() for this:

<?php
$filename = 'yourfile.js';
$content = file_get_contents( $filename );

$search = '"8:20am|8:20am"';
$pattern = '/^(\s*times\[1\]\s*=\s*\[.*)(' . 
           preg_quote($search) .
           ',?\s*)(.*\]\s*;?)$/m';

$content = preg_replace( $pattern, '\1\3', $content ); 

file_put_contents( $filename, $content );
?>

结果:

var daylist = document.checkout.checkoutDay
var timelist = document.checkout.times
var times = new Array()
times[1]=["8:00am|8:00am", "8:40am|8:40am", "9:00am|9:00am"]

常规前pression是建立相当复杂,要允许符合一定的灵活性。它允许任意空白(这将是有效的JS以及)并移除逗号,如果该值是在列表的中间。请注意,前pression还产生有效的结果,当没有逗号。 (当你想从列表中删除最后一个元素)

The regular expression is built rather complex, to allow some flexibility in matching. it allows arbitrary whitespace (which would be valid to JS as well) and removes the comma, if the value is in the middle of the list. Note that the expression also produces a valid result when there is no comma. (when you want to remove the last element from the list)

这篇关于如何删除一个字符串的特定部分的JavaScript文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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