PHP: Preg replace string with nothing - php

I'm new to preg_replace() and I've been trying to get this to work, I couldn't so StackOverflow is my last chance.
I have a string with a few of these:
('pm_IDHERE', 'NameHere');">
I want it to be replaced with nothing, so it would require 2 wildcards for NameHere and pm_IDHERE.
But I've tried it and failed myself, so could someone give me the right code please, and thanks :)

Update:
You are almost there, you just have to make the replacement an empty string and escape the parenthesis properly, otherwise they will be treated as capture group (which you don't need btw):
$str = preg_replace("#\('pm_.+?', '.*?'\);#si", "", $str);
You probably also don't need the modifiers s and i but that is up to you.
Old answer:
Probably str_replace() is sufficient:
$str = "Some string that contains pm_IDHERE and NameHere";
$str = str_replace(array('pm_IDHERE', 'NameHere'), '', $str);
If this is not what you mean and pm_IDHERE is actually something like pm_1564 then yes, you probably need regular expressions for that. But if NameHere has no actual pattern or structure, you cannot replace it with regular expression.
And you definitely have to explain better what kind of string you have and what kind of string you have want to replace.

Related

PHP preg_replace pattern only seems to work if its wrong?

I have a string that looks like this
../Clean_Smarty_Projekt/tpl/templates_c\.
../Clean_Smarty_Projekt/tpl/templates_c\..
I want to replace ../, \. and \.. with a regulare expression.
Before, I did this like this:
$result = str_replace(array("../","\..","\."),"",$str);
And there it (pattern) has to be in this order because changing it makes the output a little buggy. So I decided to use a regular expression.
Now I came up with this pattern
$result = preg_replace('/(\.\.\/)|(\\[\.]{1,2})/',"",$str);
What actually returns only empty strings...
Reason: (\\[\.]{1,2})
In Regex101 its all ok. (Took me a couple of minutes to realize that I don't need the /g in preg_replace)
If I use this pattern in preg_replace I have to do (\\\\[\.]{1,2}) to get it to work. But that's obviously wrong because im not searching for two slashes.
Of course I know the escaping rulse (escaping slashes).
Why doesn't this match correctly ?
I suggest you to use a different php delimiter. Within the / delimiter, you need to use three \\\ or four \\\\ backslashes to match a single backslash.
$string = '../Clean_Smarty_Projekt/tpl/templates_c\.'."\n".'../Clean_Smarty_Projekt/tpl/templates_c\..';
echo preg_replace('~\.\./|\\\.{1,2}~', '', $string)
Output:
Clean_Smarty_Projekt/tpl/templates_c
Clean_Smarty_Projekt/tpl/templates_c

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);

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.

Replacing a string inside a string in PHP

I have strings in my application that users can send via a form, and they can optionally replace words in that string with replacements that they also specify. For example if one of my users entered this string:
I am a user string and I need to be parsed.
And chose to replace and with foo the resulting string should be:
I am a user string foo I need to be parsed.
I need to somehow find the starting position of what they want to replace, replace it with the word they want and then tie it all together.
Could anyone write this up or at least provide an algorithm? My PHP skills aren't really up to the task :(
Thanks. :)
$result = preg_replace('/\band\b/i', 'foo', $subject);
will find all occurences of and where it's a word on its own and replace it with foo. \b ensures that there is a word boundary before and after and.
use preg_replace. You don't need to think so hard about this though you will have to learn a little bit about regexes. :)
Read up on str_replace, or for more complex replacements on Regular Expressions and preg_replace.
Examples for both:
<?php
$str = 'I am a user string and I need to be parsed.';
echo str_replace( 'and', 'foo', $str ) . "\n";
echo preg_replace( '/and/', 'foo', $str ) . "\n";
?>
In response to the comments of this answer, note that both examples above will replace every occurrence of the search string (and), even when it happens to be within another word.
To take care of that you either have to add the word separators to the str_replace call (see the comment of an example), but this will get quite complicated when you want to take care of all common word separators (space, commas, dots, exclamation marks, question marks etc.).
An easier to way to fix this problem is to use the power of regular expressions and make sure, the actual search string is not found within another word. See Tim Pietzcker's example below for a possible solution.

How to write regex to find one directory in a URL?

Here is the subject:
http://www.mysite.com/files/get/937IPiztQG/the-blah-blah-text-i-dont-need.mov
What I need using regex is only the bit before the last / (including that last / too)
The 937IPiztQG string may change; it will contain a-z A-Z 0-9 - _
Here's what I tried:
$code = strstr($url, '/http:\/\/www\.mysite\.com\/files\/get\/([A-Za-z0-9]+)./');
EDIT: I need to use regex because I don't actually know the URL. I have string like this...
a song
more text
oh and here goes some more blah blah
I need it to read that string and cut off filename part of the URLs.
You really don't need a regexp here. Here is a simple solution:
echo basename(dirname('http://www.mysite.com/files/get/937IPiztQG/the-blah-blah-text-i-dont-need.mov'));
// echoes "937IPiztQG"
Also, I'd like to quote Jamie Zawinski:
"Some people, when confronted with a problem, think 'I know, I'll use regular expressions.' Now they have two problems."
This seems far too simple to use regex. Use something similar to strrpos to look for the last occurrence of the '/' character, and then use substr to trim the string.
/http:\/\/www.mysite.com\/files\/get\/([^/]+)\/
How about something like this? Which should capture anything that's not a /, 1 or more times before a /.
The greediness of regexp will assure this works fine ^.*/
The strstr() function does not use a regular expression for any of its arguments it's the wrong function for regex replacement.
Are you thinking of preg_replace()?
But a function like basename() would be more appropriate.
Try this
$ok=preg_match('#mysite\.com/files/get/([^/]*)#i',$url,$m);
if($ok) $code=$m[1];
Then give a good read to these pages
http://www.php.net/preg_match
preg_replace
Note
the use of "#" as a delimiter to avoid getting trapped into escaping too many "/"
the "i" flag making match insensitive
(allowing more liberal spellings of the MySite.com domain name)
the $m array of captured results

Categories