Exact string replacement in php - php

I'm looking for a way to replace a string in php that exactly matches with the subject.
For example I got a file named 'hello-world.txt' having three lines:
'http://www.example.com/'
'http://www.example.com/category/'
'http://www.example.com/tag/name/'
and I need to replace the 'http://www.example.com/' with 'http://www.example2.com'
$string=file_get_contents('hello-world.txt');
$string=str_replace('http://www.example.com/','http://www.example2.com',$string);
echo $string;
I will be getting a result similar to this:
'http://www.example2.com/'
'http://www.example2.com/category/'
'http://www.example2.com/tag/name/'
But What I actually need is something like this:
'http://www.example2.com/'
'http://www.example.com/category/'
'http://www.example.com/tag/name/'
Please Help!!!!

You can use preg_replace with the m modifier as:
$string=preg_replace('~^http://www\.example\.com/$~m','http://www.example2.com',$string);
Code In Action

First check if the current line is what you're looking for. If not, just spit it back out.

Either $string=str_replace("'http://www.example.com/'", "'http://www.example2.com'", $string); since in your example you have single quotes around each line or use preg_replace like this:
$string=preg_replace('/^http:\/\/www\.example\.com\/$/', 'http://www.example2.com/', $string);
... if those single quotes aren't supposed to be there. The $ at the end of the regex means the end of the line and the ^ means the beginning of the line. Periods and / need to be escaped hence the \. and \/
I haven't tested this code. Here is a link to preg_replace() http://php.net/manual/en/function.preg-replace.php

Related

Using regex replace a string with the same string with quotes (") removed using php

I have a multi-line string shown below -
?a="text1
?bc="text23
I need to identify a pattern like using below regex
'/[?][a-z^A-Z]+[=]["]/'
and replace my string by just remove the double quote (") in it, expected output is shown below
?a=text1
?b=text23
Please help in solving the above issue using php.
Capture everything except the quote in a capture group () and replace:
$string = preg_replace('/([?][a-z^A-Z]+[=])["]/', '$1', $string);
But you really don't need all those character classes []:
/(\?[a-z^A-Z]+=)"/
I will give another solution because i see the php tag also. So let's say you have these:
$a='"text1';
$b='"text2';
if i echo them i get
"text1
"text2
in order to get rid of double quote there is a function trim in php that you can use like that:
echo trim($a,'"');
echo trim($b,'"');
the results will be
text1
text2
I dont think you need regex in this occasion as long as you use php. Php can take care of those small things without bother with complex regex expressions.

preg_match dose not work correctly in php

all,
I am using preg_match to filter some data, and it is strange that, it dose not work correctly. I am new to regex, and I used a php live regex website to check my regex, which works correctly. So I have no idea what is wrong here.
I would like to have preg_match to find something like "a\_b" in the $string:
$string="aaa\_bbb:ccc"
if(preg_match("/[a-zA-Z]\\_[a-zA-Z]/", $string)){
$snew = str_replace('\_', "_", $string);
}
But it is strange that even I have a $string like in this example above, the result of preg_match is 0. But when I change it to
preg_match("/\\_[a-zA-Z]/", $string)
It works fine and return 1. But of course that is not what I want. Any idea?
Thanks very much~
You don't really need the preg_match at all, from what I can see.
However the problem you're having with it is to do with escaping.
You have this: "/[a-zA-Z]\\_[a-zA-Z]/"
You've correctly identified that the backslash needs to be escaped, however, you've missed a subtle issue:
Regular expressions in PHP are strings. This means that you need to escape it as a string as well as a regular expression. In effect, this means that to correctly escape a backslash so it is matched as an actual backslash character in your pattern, you actually need to have four backslashes.
"/[a-zA-Z]\\\\_[a-zA-Z]/"
It's not pretty, but that's how it is.
Hope that helps.
use:
if(preg_match("/[a-zA-Z]\\\\_[a-zA-Z]/", $string))
instead
You don't need the preg_match altogether, instead just do a replace using this regex:
/([a-zA-Z])\\\\_([a-zA-Z])/
and then replace with $1_$2, like this:
$result = preg_replace("/([a-zA-Z])\\\\_([a-zA-Z])/", "$1_$2$, $string);

how to use preg_replace to replace all ocurrences of a given pattern?

I have a pattern (a slash followed by 1 or more dashes) inside strings that could occur many times like
/hi/--hello/-hi
I want to replace it with
/hi/hello/hi
I have tried
$str = preg_replace('/\/-+/', '/', $subject);
but this does not seem to be working properly. Am I missing something. I use http://www.debuggex.com/ to test my regex and \/-+ does not seem to match the string.
The reason this doesn't work in debuggex.com is that you don't have to put the delimiters on this site.
Remove the slashes at the begining and at the end from the input box.
Write only: \/-+ or /-+ since you don't need to escape the slashes.

PHP Regex: match text urls until space or end of string

This is the text sample:
$text = "asd dasjfd fdsfsd http://11111.com/asdasd/?s=423%423%2F gfsdf http://22222.com/asdasd/?s=423%423%2F
asdfggasd http://3333333.com/asdasd/?s=423%423%2F";
This is my regex pattern:
preg_match_all( "#http:\/\/(.*?)[\s|\n]#is", $text, $m );
That match the first two urls, but how do I match the last one? I tried adding [\s|\n|$] but that will also only match the first two urls.
Don't try to match \n (there's no line break after all!) and instead use $ (which will match to the end of the string).
Edit:
I'd love to hear why my initial idea doesn't work, so in case you know it, let me know. I'd guess because [] tries to match one character, while end of line isn't one? :)
This one will work:
preg_match_all('#http://(\S+)#is', $text, $m);
Note that you don't have to escape the / due to them not being the delimiting character, but you'd have to escape the \ as you're using double quotes (so the string is parsed). Instead I used single quotes for this.
I'm not familar with PHP, so I don't have the exact syntax, but maybe this will give you something to try. the [] means a character class so |$ will literally look for a $. I think what you'll need is another look ahead so something like this:
#http:\/\/(.*)(?=(\s|$))
I apologize if this is way off, but maybe it will give you another angle to try.
See What is the best regular expression to check if a string is a valid URL?
It has some very long regular expressions that will match all urls.

Problem using regex to remove number formatting in PHP

I'm having this issue with a regular expression in PHP that I can't seem to crack. I've spent hours searching to find out how to get it to work, but nothing seems to have the desired effect.
I have a file that contains lines similar to the one below:
Total','"127','004"','"118','116"','"129','754"','"126','184"','"129','778"','"128','341"','"127','477"','0','0','0','0','0','0
These lines are inserted into INSERT queries. The problem is that values like "127','004" are actually supposed to be 127,004, or without any formatting: 127004. The latter is the actual value I need to insert into the database table, so I figured I'd use preg_replace() to detect values like "127','004" and replace them with 127004.
I played around with a Regular Expression designer and found that I could use the following to get my desired results:
Regular Expression
"(\d+)','(\d{3})"
Replace Expression
$1$2
The line on the top of this post would end up like this: (which is what I am after)
Total','127004','118116','129754','126184','129778','128341','127477','0','0','0','0','0','0
This, however, does not work in PHP. Nothing is being replaced at all.
The code I am using is:
$line = preg_replace("\"(\d+)','(\d{3})\"", '$1$2', $line);
Any help would be greatly appreciated!
There are no delimiters in your regex. Delimiters are required in order for PHP to know what is the pattern to match and what is a pattern modifier (e.g. i - case-insensitive, U - ungreedy, ...). Use a character that doesn't occur in your pattern, typically you'll see a slash '/' used.
Try this:
$line = preg_replace("/\"(\d+)','(\d{3})\"/", '$1$2', $line);
You forgot to wrap your regular expression in front-slashes. Try this instead:
"/\"(\d+)','(\d{3})\"/"
use preg_replace("#\"(\d+)','(\d+)\"#", '$1$2', $s); instead of yours

Categories