PHP: preg_replace() "inch" doublequotes with double-singlequotes? - php

It's been a couple years since I used RegEx, and being fairly novice even back then, I'm getting stumped on what I thought would be an easy one.
I have two data sources which I need to compare, and one has double-quotes " denoting inches while the other uses doubled-single-quotes ''.
As I'm iterating through, I need to convert the single-doubles " to double-singles ''.
I started off playing with preg_match(), and once I had a pattern returning TRUE, I moved it to preg_replace(). Looks like my feeble attempt is not holding up, though.
Let's take a look:
$str = 'PRE-301 1/8" ID 48" BX';
preg_replace( '/(\d+)\"/', "\1''", $str );
echo '<pre>',var_dump($str),'</pre>';
My goal is to get a string(24) "PRE-301 1/8'' ID 48'' BX". What I am getting, though, is just the original string(22) "PRE-301 1/8" ID 48" BX" back.

You are not assigning the value back, and you need to change \1 to $1 in your replacement.
$str = preg_replace('/(\d+)"/', "$1''", $str);
Live Demo
Note: You can remove the backslash before your quotes, it's not neccessary here. And if your strings are always like this, you can use just replace the quotes alone using str_replace():
$str = str_replace('"', "''", $str);

Couple of things here.
preg_replace doesn't change the string in place, but returns a value. So you are looking for:
$new_str = preg_replace(...
Double quote (and single for that matter) are not metacharacters in Regex, so you are free to leave off the \ in front of the ". It won't hurt anything, but it's a bit more readable, which is nice with Regex!

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.

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

Is there a better way to strip/form this string in PHP?

I am currently using what appears to be a horribly complex and unnecessary solution to form a required string.
The string could have any punctuation and will include slashes.
As an example, this string:
Test Ripple, it\'s a comic book one!
Using my current method:
str_replace(" ", "-", trim(preg_replace('/[^a-z0-9]+/i', ' ', str_replace("'", "", stripslashes($string)))))
Returns the correct result:
Test-Ripple-its-a-comic-book-one
Here is a breakdown of what my current (poor) solution is doing in order to achieve the desired output:-
Strip all slashes from the string
remove any apostrophes with str_replace
remove any remaining punctuation using preg_replace and replace it with whitespace
Trim off any extra whitespace from the beginning/end of string which may have been caused by punctuation.
Replace all whitespace with '-'
But there must be a better and more efficient way. Can anyone help?
Personally it looks fine to me however I would make one small change.
Change
preg_replace("/[^a-z0-9]+/i"
to the following
preg_replace("/[^a-zA-Z0-9\s]/"

Search and Replace with Regex

I am trying to search through text for a specific word and then add a html tag around that word.For example if i had the string "I went to the shop to buy apples and oranges" and wanted to add html bold tags around apples.
The problem, the word i search the string with is stored in a text file and can be uppercase,lowercase etc.When i use preg_replace to do this i manage to replace it correctly adding the tags but for example if i searched for APPLES and the string contained "apples" it would change the formatting from apples to APPLES, i want the format to stay the same.
I have tried using preg_replace but i cant find a way to keep the same word casing.This is what i have:
foreach($keywords as $value)
{
$pattern = "/\b$value\b/i";
$replacement = "<b>$value</b>";
$new_string = preg_replace($pattern, $replacement, $string);
}
So again if $value was APPLES it would change every case format of apples in the $string to uppercase due to $replacemant having $value in it which is "APPLES".
How could i achieve this with the case format staying the same and without having to do multiple loops with different versions of case format?
Thanks
Instead of using $value verbatim in the replacement, you can use the literal strings \0 or $0. Just as \n/$n, for some integer n, refers back to the nth capturing group of parentheses, \0/$0 is expanded to the entire match. Thus, you'd have
foreach ($keywords as $value) {
$new_string = preg_replace("/\\b$value\\b/i", '<b>$0</b>', $string);
}
Note that '<b>$0</b>' uses single quotes. You can get away with double quotes here, because $0 isn't interpreted as a reference to a variable, but I think this is clearer. In general, you have to be careful with using a $ inside a double-quoted string, as you'll often get a reference to an existing variable unless you escape the $ as \$. Similarly, you should escape the backslash in \b inside the double quotes for the pattern; although it doesn't matter in this specific case, in general backslash is a meaningful character within double quotes.
I might have misunderstood your question, but if what you are struggling on is differentiating between upper-case letter (APPLE) and lower-case letter (apple), then the first thing you could do is convert the word into upper-case, or lower-case, and then run the tests to find it and put HTML tags around it. That is just my guess and maybe I completely misunderstood the question.
In the code exists offtopic error: the result value have been rewritten on not first loop iteration. And ending value of $new_string will be only last replacement.

PHP: Preg replace string with nothing

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.

Categories