replace string (variables) php - php

I have a string like this: foo($bar1, $bar2)
How to I replace each variable with <span>$variable</span> with regexp?
This is my try (not working):
$row['name'] = preg_replace("/\$\w+/S", "<span>$1</span>", $row['name']);
I only want the variables to be replaced and have a span around them, I don't want commas or spaces to be replaced.
What I want is to have my string foo($bar1, $bar2) to be replaced with foo(<span>$bar1</span>, <span>$bar2</span>) ($bar1 and $bar2 are not variables, it's plain text).

Here are some problems I can see:
Since you are using double quotes for the regex,
you need to escape the $ using two \ as \\$.
Alternatively you can just use single
quote and use \$.
You are using $1 in the replacement
but you are not having any group in
the regex. So have ( ) around
\$\w+
So try:
$str = preg_replace('/(\$\w+)/', "<span>$1</span>", $str);
or
$str = preg_replace("/(\\$\w+)/", "<span>$1</span>", $str);
See it.

Related

Remove backwards slashes in string

When running a function which returns a string, I end up with backwards-slashes before a quotation marks, like this:
$string = get_string();
// returns: Example
I suspect it is some type of escaping happening somewhere. I know I can string replace the backwards-slash, but I suppose in these cases, there is some type of unescape function you run?
You only need to escape quotes when it matches your starting/ending delimiter. This code should work properly:
$string = 'Example';
If your string is enclosed in single quotes ', then " doesn't need to be escaped. Likewise, the opposite is true.
Avoid using stripslashes(), as it could cause issues if single quotes need to contain slashes. A simple find/replace should work for you:
$string = 'Example';
$string = str_replace($string, '\"', '"');
echo $string; //echos Example
<?php
$string = 'Example';
echo stripslashes($string);
?>

PHP: preg_replace() on NameSpace

I'm trying to get the parent "elements" name as string from a PHP namespace in a string, the ideia is to do:
Input: \Base\Util\Review; Desired Output: \Base\Util;
My main problem here is how can I deal with the backslash escaping in the regex expression, so far I can make it work with the normal slash:
$ns = "/Base/Util/Review";
print preg_replace("#\/[^/]*$#", '', $ns);
// Outputs => /Base/Util
Thank you.
This should work:
$s = '\\Base\\Util\\Review';
$r = preg_replace('~\\\\[^\\\\]*$~', '', $s);
//=> \Base\Util
You can do it without preg_replace
$ns = "\Base\Util\Review";
print implode('\\', array_slice(explode('\\',$ns),0,-1));
Another option:
$ns = "\Base\Util\Review";
print substr($ns,0,strrpos($ns,'\\'));
Try this
print preg_replace("#\\\[^\\\]*$#", '', $ns)
You will have to write four backslashes for each literal backslash:
$regex = '#\\\\#'; // regex matching one backslash
You need to escape each \ once to escape its special meaning in the regex, and again escape each \ once to escape its meaning in the PHP string literal.

remove double square brackets and keep the string

I need to remove all square brackets from a string and keep the string. I've been looking around but all topic OP's want to replace the string with something.
So: [[link_to_page]]
should become: link_to_page
I think I should use php regex, can someone assist me?
Thanks in advance
You can simply use a str_replace.
$string = str_replace(array('[[',']]'),'',$string);
But this would get a '[[' without a ']]' closure. And a ']]' without a '[[' opening.
It's not entirely clear what you want - but...
If you simply want to "remove all square brackets" without worrying about pairing/etc then a simple str_replace will do it:
str_replace( array('[',']') , '' , $string )
That is not (and doesn't need to be) a regex.
If you want to unwrap paired double brackets, with unknown contents, then a regex replace is what you want, which uses preg_replace instead.
Since [ and ] are metacharacters in regex, they need to be escaped with a backslash.
To match all instances of double-bracketed text, you can use the pattern \[\[\w+\[\] and to replace those brackets you can put the contents into a capture group (by surrounding with parentheses) and replace all instances like so:
$output = preg_replace( '/\[\[(\w+)\[\]/' , '$1' , $string );
The \w matches any alphanumeric or underscore - if you want to allow more/less characters it can be updated, e.g. \[\[([a-z\-_]+)\[\] or whatever makes sense.
If you want to act on the contents of the square brackets, see the answer by fluminis.
You can use preg_replace:
$repl = preg_replace('/(\[|\]){2}/', '', '[[link_to_page]]');
OR using str_replace:
$repl = str_replace(array('[[', ']]'), '', '[[link_to_page]]');
If you want only one match :
preg_match('/\[\[([^\]]+)\]\]/', $yourText, $matches);
echo $matches[1]; // will echo link_to_page
Or if you want to extract all the link from a text
preg_match_all('/\[\[([^\]]+)\]\]/', $yourText, $matches);
foreach($matches as $link) {
echo $link[1];
}
How to read '/\[\[([^\]]+)\]\]/'
/ start the regex
\[\[ two [ characters but need to escape them because [ is a meta caracter
([^\]]+) get all chars that are not a ]
\]\] two ] characters but need to escape them because ] is a meta caracter
/ end the regex
Try
preg_replace(/(\[\[)|(\]\])/, '', $string);

Remove backslash \ from string using preg replace of php

I want to remove the backslash alone using php preg replace.
For example: I have a string looks like
$var = "This is the for \testing and i want to add the # and remove \slash alone from the given string";
How to remove the \ alone from the corresponding string using php preg_replace
why would you use preg_replace when str_replace is much easier.
$str = str_replace('\\', '', $str);
To use backslash in replacement, it must be doubled (\\\\ PHP string) in preg_replace
echo preg_replace('/\\\\/', '', $var);
You can also use stripslashes() like,
<?php echo stripslashes($var); ?>
$str = preg_replace('/\\\\(.?)/', '$1', $str);
This worked for me!!
preg_replace("/\//", "", $input_lines);

Special (escaped) characters in replacements array in preg_replace get escaped

I’m trying to modify a string of the following form where each field is delimited by a tab except for the first which is followed by two or more tabs.
"$str1 $str2 $str3 $str4 $str5 $str6"
The modified string will have each field wrapped in HTML table tags, and be on its own, indented line as so.
"<tr>
<td class="title">$str1</td>
<td sorttable_customkey="$str2"></td>
<td sorttable_customkey="$str3"></td>
<td sorttable_customkey="$str4"></td>
<td sorttable_customkey="$str5"></td>
<td sorttable_customkey="$str6"></td>
</tr>
"
I tried using code like the following to do it.
$patterns = array();
$patterns[0]='/^/';
$patterns[1]='/\t\t+/';
$patterns[2]='/\t/';
$patterns[3]='/$/';
$replacements = array();
$replacements[0]='\t\t<tr>\r\n\t\t\t<td class="title">';
$replacements[1]='</td>\r\n\t\t\t<td sorttable_customkey="';
$replacements[2]='"></td>\r\n\t\t\t<td sorttable_customkey="';
$replacements[3]='"></td>\r\n\t\t</tr>\r\n';
for ($i=0; $i<count($lines); $i++) {
$lines[$i] = preg_replace($patterns, $replacements, $lines[$i]);
}
The problem is that the escaped characters (tabs and newlines) in the replacement array remain escaped in the destination string and I get the following string.
"\t\t<tr>\r\n\t\t\t<td class="title">$str</td>\r\n\t\t\t<td sorttable_customkey="$str2"></td>\r\n\t\t\t<td sorttable_customkey="$str3"></td>\r\n\t\t\t<td sorttable_customkey="$str4"></td>\r\n\t\t\t<td sorttable_customkey="$str5"></td>\r\n\t\t\t<td sorttable_customkey="$str6"></td>\r\n\t\t</tr>\r\n"
Strangely, this line I tried earlier on does work:
$data=preg_replace("/\t+/", "\t", $data);
Am I missing something? Any idea how to fix it?
You need double quotes or heredocs for the replacement string - PCRE only parses those escape characters in the search string.
In your working example preg_replace("/\t+/", "\t", $data) those are both literal tab characters because they're in double quotes.
If you changed it to preg_replace('/\t+/', '\t', $data) you can observe your main problem - PCRE understands that the \t in the search string represents a tab, but doesn't for the one in the replacement string.
So by using double quotes for the replacement, e.g. preg_replace('/\t+/', "\t", $data), you let PHP parse the \t and you get the expected result.
It is slightly incongruous, just something to remember.
Your $replacements array has all its strings decalred as single-quoted strings.
That means that escaped characters won't scape (except \').
It is not related directly to PCRE regular expressions, but to how PHP handles strings.
Basically you can type strings like these:
<?php # String test
$value = "substitution";
$str1 = 'this is a $value that does not get substituted';
$str2 = "this is a $value that does not remember the variable"; # this is a substitution that does not remember the variable
$str3 = "you can also type \$value = $value" # you can also type $value = substitution
$bigstr =<<< MARKER
you can type
very long stuff here
provided you end it with the single
value MARKER you had put earlier in the beginning of a line
just like this:
MARKER;
tl;dr version: problem is single quotes in the $replacements and $patterns that should be double quotes

Categories