Regex is failing to capture values inside [...][...] - php

I am trying to change color of a text in my string :
my string :
$message="I have a [red][car]";
I want to capture the values inside the first [...] and second [...] and then use it in
<b style='color:color'>car</b>
to change the text color according to the value of first [...]
So far I have :
echo preg_replace("/\[([^\]]+)\]\[([^\]+])\]/i","<b style='color:$1'>$2</b>",$message);
But it's not working, the orignal string is returned as output. I don't know where my regex failed.
Please help!

The corrected regex is:
'/\[([^\]]+)]\[([^\]]+)]/'
See regex demo
Note that you do not have to escape ] outside the character class and no need in /i modifier as there are not letters in your pattern. Also, to properly escape special regex characters, you either need to double escapes in the double quoted string, or use a single quoted string.
IDEONE demo:
$message="I have a [red][car]";
echo preg_replace('/\[([^\]]+)]\[([^\]]+)]/',"<b style='color:$1'>$2</b>",$message);
// => I have a <b style='color:red'>car</b>

$message="I have a [red][car]";
echo preg_replace("/[^\[]+\[([^\]]+)\]\[([^\]]+)\]/i","<b style='color:$1'>$2</b>",$message);

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 a back slash

$pattern = '/\\\p\\\/';
if (preg_match($pattern, "\p\")) {
echo "Correct";
} else {
echo "Incorrect";
}
I don't understand the first \\\p.
Why \\p does not work?
Your pattern is wrong. pattern \\p\\ matches the string \p\. But \\\p\\\ doesn't matches anything.
DEMO
If you want to match the string \\p\\, your pattern should be \\\\p\\\\.
DEMO
Note that "\p\" is not a valid string:
The final \" escapes the quote, so that the string is not terminated
The \p matches a literal p character, which is not what you intended
If you want to say \p\ in a string, you have to write it like this: "\\p\\"
To match \p\, use:
$regex = '~\\\\p\\\\~';
echo (preg_match($regex,"\\p\\")) ? "Matches" : "Doesn't Match";
See the output at the bottom of the online demo.
The problem here is that both strings and regular expressions use escape characters and they need to be doubled in order to effect the intended behaviour.
So, in this case you need four backslashes in the regular expression and two of them in the search string:
if (preg_match('/\\\\p\\\\/', '\\p\\')) {
echo "Hurray!\n";
}
The reason why '/\\\p\\\/' works is because \p and \/ have no special meaning in a single quoted string and so the backslash is printed verbatim. In other words, PHP corrects your string to have the correct meaning; that said, you should use the correct number of escape characters.
Btw, "\\p\" is just plain wrong and will cause a parse error; I'm going to assume that this was a typo.

addslashes() only if slashes are not added from before

I'm getting a lot of text values from my database that I need to output with slashes added before characters that need to be quoted.
Problem is that some of the data already has the slashes added there from before, whilst some of it doesn't.
How can I add slashes using for example addslashes() - but at the same time make sure that it doesn't add an extra slash in the cases where the slash is already added?
Example:
Input: test
Output should be: test
Input: test
Output should be: test
This is PHP 5.3.10.
If you know that you don't have any double slashes, simply run addslashes() and then replace all \\ with \.
If you have something like this:
test
Using addslashes(), the output will be:
test
So, you may need to replace every occurrence of more than one \ to be sure
function addslashes($string) {
return preg_replace('/([^\\\\])\"/','$1\"',$string);
}
The answer of Qaflanti is correct but I would like to make it more complete, if you want to escape both single and double quotes.
First option :
function escape_quotes($string) {
return preg_replace("/(^|[^\\\\])(\"|')/","$1\\\\$2", $string);
}
Input
I love \"carots\" but "I" don't like \'cherries\'
Output
I love \"carots\" but \"I\" don\'t like \'cherries\'
Explanation :
The \ has a special meaning inside a quoted expression and will escape the following character in the string, so while you would need to write \\ in a regex to search for the backslash character, in php you need to escape those two backslashes also, adding up to a total of 4 backslashes.
So with that in mind, the first capturing group then searches for a single character that is not a backslash (and not two or four backslashes as misleading as it is)
The second capturing group will search for a double or a single quote
exactly once.
So this finds unescaped quotes (double and single) and add a backslash before the quote thus escaping it.
Second option :
Or it might just be best for you to convert them to html entities from the start :
function htmlentities_quotes($string) {
return str_replace(array('"', "'"), array(""", "&apos;"), $string);
}
And then you just have to use the php function htmlspecialchars_decode($string); to revert it back to how it was.
Input
I love "carots" but "I" don't like 'cherries'
Output
I love "carots" but "I" don&apos;t like
&apos;cherries&apos;

regex with special characters?

i am looking for a regex that can contain special chracters like / \ . ' "
in short i would like a regex that can match the following:
may contain lowercase
may contain uppercase
may contain a number
may contain space
may contain / \ . ' "
i am making a php script to check if a certain string have the above or not, like a validation check.
The regular expression you are looking for is
^[a-z A-Z0-9\/\\.'"]+$
Remember if you are using PHP you need to use \ to escape the backslashes and the quotation mark you use to encapsulate the string.
In PHP using preg_match it should look like this:
preg_match("/^[a-z A-Z0-9\\/\\\\.'\"]+$/",$value);
This is a good place to find the regular expressions you might want to use.
http://regexpal.com/
You can always escape them by appending a \ in front of the special characters.
try this:
preg_match("/[A-Za-z0-9\/\\.'\"]/", ...)
NikoRoberts is 100% correct.
I would only add the following suggestion: When creating a PHP regex pattern string, always use: single-quotes. There are far fewer chars which need to be escaped (i.e. only the single quote and the backslash itself needs to be escaped (and the backslash only needs to be escaped if it appears at the end of the string)).
When dealing with backslash soup, it helps to print out the (interpreted) regex string. This shows you exactly what is being presented to the regex engine.
Also, a "number" might have an optional sign? Yes? Here is my solution (in the form of a tested script):
<?php // test.php 20110311_1400
$data_good = 'abcdefghijklmnopqrstuvwxyzABCDE'.
'FGHIJKLMNOPQRSTUVWXYZ0123456789+- /\\.\'"';
$data_bad = 'abcABC012~!###$%^&*()';
$re = '%^[a-zA-Z0-9+\- /\\\\.\'"]*$%';
echo($re ."\n");
if (preg_match($re, $data_good)) {
echo("CORRECT: Good data matches.\n");
} else {
echo("ERROR! Good data does NOT match.\n");
}
if (preg_match($re, $data_bad)) {
echo("ERROR! Bad data matches.\n");
} else {
echo("CORRECT: Bad data does NOT match.\n");
}
?>
The following regex will match a single character that fits the description you gave:
[a-zA-Z0-9\ \\\/\.\'\"]
If your point is to insure that ONLY characters in this range of characters are used in your string, then you can use the negation of this which would be:
[^a-zA-Z0-9\ \\\/\.\'\"]
In the second case, you could use your regex to find the bad stuff (that you don't want to be included), and if it didn't find anything then your string pattern must be kosher, because I'm assuming that if you find one character that is not in the proper range, then your string is not valid.
so to put it in PHP syntax:
$regex = "[^a-zA-Z0-9\ \\\/\.\'\"]"
if preg_match( $regex, ... ) {
// handle the bad stuff
}
Edit 1:
I've completely ignored the fact that backslashes are special in php double-quoted strings, so here is a correcting to the above code:
$regex = "[^a-zA-Z0-9\\ \\\\\\/\\.\\'\\\"]"
If that doesn't work it shouldn't take too much for someone to debug how many of the backslashes need to be escaped with a backslash, and what other characters need also to be escaped....

Removing first newline preg_replace

I'm writing some PHP to convert BBcode to HTML.
I would like to convert this BBcode:
[quote]
Hello World
[/quote]
to the following:
<blockquote>Hello World</blockquote>
The preg_replace function that I'm using to perform this is:
preg_replace("/\[quote\](.+?)\[\/quote\]/s", "<blockquote>\\1</blockquote>", $bbCode);
This almost does everything I need it to, but my problem is that it carries through the \n's from before and after 'Hello World', and produces:
<blockquote>
Hello World
</blockquote>
Any ideas how I could fix this? All help very much appreciated.
Try this regular expression:
/\[quote\]\s*(.+?)\s*\[\/quote\]/s
You need to escape backslashes inside of double-quotes. Instead of "\[", you need "\\[".
A possibility would be to use the 'e' regex-modifier, to call, for instance, the trim function on the string.
Quoting that page of the manual :
e (PREG_REPLACE_EVAL) If this modifier is set, preg_replace()
does normal substitution of
backreferences in the replacement
string, evaluates it as PHP code, and
uses the result for replacing the
search string. Single quotes, double
quotes, backslashes (\) and NULL
chars will be escaped by backslashes
in substituted backreferences.
Only preg_replace() uses this
modifier; it is ignored by other PCRE
functions.
For instance, this code, only slightly different from yours :
$bbCode = <<<STR
[quote]
Hello World
[/quote]
STR;
$output = preg_replace("/\[quote\](.+?)\[\/quote\]/es", "'<blockquote>' . trim('\\1') . '</blockquote>'", $bbCode);
var_dump($output);
Would give you :
string '<blockquote>Hello World</blockquote>' (length=36)
ie, the trim function is called on what was matched -- note it will remove all white-spaces at the beginning and end of your string ; not only newlines, but also spaces and tabulations.
(For instance, you can take a look at Example #4 on the manual page of preg_replace)
(It's maybe a bit overkill in this case, should I add -- but it's nice to know anyway)

Categories