我有一个这样的文本文件:
ip_rule '100 120 16.54'
qos_rule '8074 4462'
info 'Updated on 2015'
我希望这个文字是这样的:
ip_rule='100 120 16.54'
qos_rule='8074 4462'
info='Updated on 2015'
因此,它只会替换''
之外的空格,并将其更改为等号=
。我怎么能用PHP做到这一点,我尝试用str_replace
替换它们,但它取代了整个空格。
答案 0 :(得分:1)
您可以使用=
跳过规则。例如,在您当前的示例中,这将跳过单引号中的任何内容,然后查找任何水平空格(如果可以有多个,并且只应用一个+
替换,请使用'.*?'(*SKIP)(*FAIL)|\h
量词):< / p>
echo preg_replace("/'.*?'(*SKIP)(*FAIL)|\h/", '=', "ip_rule '100 120 16.54'
qos_rule '8074 4462'
info 'Updated on 2015'");
演示:https://regex101.com/r/umaQdY/1
PHP用法:
#include <iostream>
#include "stdlib.h"
using namespace std;
int main ()
{
int n; //number of array A elements
int m=1, l=1; //number of Array B and C correspondly
cout<<"Please enter n: ";
cin>>n; //number input
float *A = (float *) malloc (n*sizeof(float));//dynamic array A definition
for (int i=0;i<n;i++) //array A filling
{
cout<<"Please enter A["<<i<<"]= ";
cin>>A[i];
}
float *B = (float *) malloc (m*sizeof(float));//Array B definition with 1 element for beginning
float *C = (float *) malloc (l*sizeof(float));//Array C definition with 1 element for beginning
for (int i=0;i<n;i++)
{
if(A[i]!=0)
{
if(A[i]>0)
{
B[m-1] = A[i];
B = (float *) realloc (B, (m++)*sizeof(float));
}
else
{
C[l-1] = A[i];
C = (float *) realloc (C, (l++)*sizeof(float));
}
}
}
if(m>2) B = (float *) realloc (B, (m--)*sizeof(float)); //because arrays created with 1 extra elements
if(l>2) C = (float *) realloc (C, (l--)*sizeof(float)); //need delete last element that doesn`t have a number
for (int i=0;i<n;i++)
{
cout<<"A["<<i<<"]= "<<A[i]<<endl;
}
free(A);
cout<<endl;
for (int i=0;i<m;i++)
{
cout<<"B["<<i<<"]= "<<B[i]<<endl;
}
free(B);
cout<<endl;
for (int i=0;i<l;i++)
{
cout<<"C["<<i<<"]= "<<C[i]<<endl;
}
cout<<endl;
free(C);
return 0;
}
PHP演示:https://eval.in/663922
您可以在此处详细了解http://www.rexegg.com/regex-best-trick.html#pcrevariation。