i'm beginning in PHP and i try to remove all occurrence of a string. My string is something like that.
'This is [a test] try [it]'
What i'm trying to do is remove all occurrence of the [] with the text inside the square bracket.
I want the results to be something like:
'This is try'
.
How can i achieve that?
You could use preg_replace function.
preg_replace('~\[[^\]]*\]~', '', $string);
[^\]]* negated character class which matches any character but not of a closing bracket ], zero or more times.
Add an extra trim function to remove the leading or trailing spaces from the resultant string.
$string = 'This is [a test] try [it]';
$result = preg_replace('~\[[^\]]*\]~', '', $string);
echo trim($result, " ");
You can try this:
$myString = 'This is [a test] try [it]';
$myString = preg_replace('/\[[\w ]+\] */', '', $myString);
var_dump($myString);
Explanations:
/\[[\w ]+\]/g
\[ matches the character [ literally
[\w ]+ match a single character present in the list below
Quantifier: + Between one and unlimited times, as many times as possible, giving back as needed [greedy]
\w match any word character [a-zA-Z0-9_]
' ' the literal character ' '
\] matches the character ] literally
Related
I want to do something like stackoverflow. actually changing this style []() to this style . here is my try:
$str = '[link](#)';
$str = str_replace('[','<a href="',$str); // output: <a href="link](#)
$str = str_replace(']','">',$str); // output: <a href="link">(#)
$str = str_replace('(','',$str); // output: <a href="link">#)
$str = str_replace(')','</a>',$str); // output: #
but now, I need to change link with #, how can I do that ?
You want to take a look at preg_replace(), with this you can use a regex to replace it, e.g.
$str = preg_replace("/\[(.*?)\]\((.*?)\)/", "<a href='$2'>$1</a>", $str);
regex explanation:
\[(.*?)\]\((.*?)\)
\[ matches the character [ literally
1st Capturing group (.*?)
.*? matches any character (except newline)
Quantifier: *? Between zero and unlimited times, as few times as possible, expanding as needed [lazy]
\] matches the character ] literally
\( matches the character ( literally
2nd Capturing group (.*?)
.*? matches any character (except newline)
Quantifier: *? Between zero and unlimited times, as few times as possible, expanding as needed [lazy]
\) matches the character ) literally
I am looking to find and replace words in a long string. I want to find words that start looks like this: $test$ and replace it with nothing.
I have tried a lot of things and can't figure out the regular expression. This is the last one I tried:
preg_replace("/\b\\$(.*)\\$\b/im", '', $text);
No matter what I do, I can't get it to replace words that begin and end with a dollar sign.
Use single quotes instead of double quotes and remove the double escape.
$text = preg_replace('/\$(.*?)\$/', '', $text);
Also a word boundary \b does not consume any characters, it asserts that on one side there is a word character, and on the other side there is not. You need to remove the word boundary for this to work and you have nothing containing word characters in your regular expression, so the i modifier is useless here and you have no anchors so remove the m (multi-line) modifier as well.
As well * is a greedy operator. Therefore, .* will match as much as it can and still allow the remainder of the regular expression to match. To be clear on this, it will replace the entire string:
$text = '$fooo$ bar $baz$ quz $foobar$';
var_dump(preg_replace('/\$(.*)\$/', '', $text));
# => string(0) ""
I recommend using a non-greedy operator *? here. Once you specify the question mark, you're stating (don't be greedy.. as soon as you find a ending $... stop, you're done.)
$text = '$fooo$ bar $baz$ quz $foobar$';
var_dump(preg_replace('/\$(.*?)\$/', '', $text));
# => string(10) " bar quz "
Edit
To fix your problem, you can use \S which matches any non-white space character.
$text = '$20.00 is the $total$';
var_dump(preg_replace('/\$\S+\$/', '', $text));
# string(14) "$20.00 is the "
There are three different positions that qualify as word boundaries \b:
Before the first character in the string, if the first character is a word character.
After the last character in the string, if the last character is a word character.
Between two characters in the string, where one is a word character and the other is not a word character.
$ is not a word character, so don't use \b or it won't work. Also, there is no need for the double escaping and no need for the im modifiers:
preg_replace('/\$(.*)\$/', '', $text);
I would use:
preg_replace('/\$[^$]+\$/', '', $text);
You can use preg_quote to help you out on 'quoting':
$t = preg_replace('/' . preg_quote('$', '/') . '.*?' . preg_quote('$', '/') . '/', '', $text);
echo $t;
From the docs:
This is useful if you have a run-time string that you need to match in some text and the string may contain special regex characters.
The special regular expression characters are: . \ + * ? [ ^ ] $ ( ) { } = ! < > | : -
Contrary to your use of word boundary markers (\b), you actually want the inverse effect (\B)-- you want to make sure that there ISN'T a word character next to the non-word character $.
You also don't need to use capturing parentheses because you are not using a backreference in your replacement string.
\S+ means one or more non-whitespace characters -- with greedy/possessive matching.
Code: (Demo)
$text = '$foo$ boo hi$$ mon$k$ey $how thi$ $baz$ bar $foobar$';
var_export(
preg_replace(
'/\B\$\S+\$\B/',
'',
$text
)
);
Output:
' boo hi$$ mon$k$ey $how thi$ bar '
How do I change the word to bold, if there is only one word on a line with a colon at the end?
data comes from at text field in mysql database, and code is php
You can capture the word and substitute surrounded by <b>
^(\w+):$
Live demo
Sample code:
$re = "/^(\\w+):$/m";
$str = "abc:\nabc\nabc:xyz\n";
$subst = '<b>$1</b>';
$result = preg_replace($re, $subst, $str);
Pattern explanation:
^ the beginning of the string
( group and capture to \1:
\w+ word characters (a-z, A-Z, 0-9, _) (1 or more times)
) end of \1
: ':'
$ before an optional \n, and the end of the string
Use this:
$replaced = preg_replace('~^\w+:$~', '<b>$0</b>', $yourstring);
Explanation
The ^ anchor asserts that we are at the beginning of the string
The \w+ matches one or more word chars
: matches the colon
The $ anchor asserts that we are at the end of the string
We replace with <b>, the overall match (referenced by $0) and </b>
I want to remove any type of special characters in a string like this:
This is, ,,, *&% a ::; demo + String. +
Need to**#!/// format:::::
!!! this.`
Output Required:
This is a demo String Need to format this
How to do this using REGEX?
Check for any repeated instance of a non-number, non-letter character and repeat with a space:
# string(41) "This is a demo String Need to format this"
$str = trim( preg_replace( "/[^0-9a-z]+/i", " ", $str ) );
Demo: http://codepad.org/hXu6skTc
/ # Denotes start of pattern
[ # Denotes start of character class
^ # Not, or negative
0-9 # Numbers 0 through 9 (Or, "Not a number" because of ^
a-z # Letters a through z (Or, "Not a letter or number" because of ^0-9
] # Denotes end of character class
+ # Matches 1 or more instances of the character class match
/ # Denotes end of pattern
i # Case-insensitive, a-z also means A-Z
Use:
preg_replace('#[^a-zA-Z0-9 ]#', '', $yourString);
If characters are not alphabet, numbers or space, it is replaced with empty string.
Example:
$yourString = 'This is, ,,, *&% a ::; demo + String. + Need to**#!/// format::::: !!! this.`';
$newStr = preg_replace('#[^a-zA-Z0-9 ]#', '', $yourString);
echo $newStr;
Result:
This is a demo String Need to format this
So you can allow more characters if you want by putting them in:
[^a-zA-Z0-9 ]
Note: Also if you don't want to allow multiple spaces between words (though they wont be shown when output in browser), you need to use this instead:
preg_replace('#[^a-zA-Z0-9]+#', ' ', $yourString);
echo preg_replace('/[^a-z]+/i', ' ', $str);
// This is a demo String Need to format this
$string = preg_replace('/[^a-z]+/i', ' ', $string);
You may also want to allow ' in your character class to have conjunctions like don't not be turned into don t:
$string = preg_replace('/[^a-z\']+/i', ' ', $string);
You might also want to trim it afterwards to remove leading and trailing whitespace:
$string = trim(preg_replace('/[^a-z\']+/i', ' ', $string));
I have string like below,
$string = "test coontevt [gallery include=\"12,24\"] first [gallery include=\"12,24\"] second";
i need to remove the string starts with [gallery to first ocuurance of it's ].
i already use this one,
$string12 = preg_replace('/[gallery.+?)+(/])/i', '', $string);
but i get empty string only.
Finally i want result for the above string is,
$string ="test coontevt first second".
How can i do this using regular expression?.
plz help me?
The character [ is a regex meta-character. TO match a literal [ you need to escape it.
$string12 = preg_replace('/\[gallery.+?\]/i', '', $string);
or
$string12 = preg_replace('/\[gallery[^\]]+\]/i', '', $string);
You need to escape the square brackets
$string12 = preg_replace('/\[gallery.+?\]/i', '', $string);
The round brackets are unnecessary so I removed them, also the quantifier between those brackets and the forward slash before the last square bracket.
To avoid multiple space in the result, I would match also the surrounding spaces and replace with 1 space.
\s+\[gallery.+?\]\s+ and replace with one space
$string12 = preg_replace('/\s+\[gallery.+?\]\s+/i', ' ', $string);
See this expression here online on Regexr
Try it like this:
$string12 = preg_replace('/\[gallery[^\]]+\]/i', '', $string);
[^\]]+ means that there can be one or more character that is not ]. And there is no need for any ( and ) if you don't want to use the backreferences.