Remove contents from a string comma and bracket - php

I want to filter a string with my requirements
$string="my super city (name , result)";
I want only result as output.
Any experts ???
Any help would be greatly appreciated.

To perform a replacement:
$result = preg_replace( '/.*?,\s*(\w+)\).*?/', '\1', $string );
In $result you have this:
result
If you want match every not-comma characters, use this regular expression instead:
/.*?,\s*([^,]+)\).*?/
1st pattern explaination:
/
.*? zero-or-more characters
, a comma
\s* zero-or-more spaces
(\w+) Group 1: one-or-more word characters
\) closing bracket
.*? zero-or-more characters
/
regex101 demo

Try this
$full = preg_replace("/[^A-Za-z ]/", '', $string);
if you need numerics(0-9) also, then try
$full = preg_replace("/[^A-Za-z0-9 ]/", '', $string);
EDIT:
Then
$exp = explode(" ", $full);
echo $exp[count($exp)-1];

Related

Php make spaces in a word with a dash

I have the following string:
$thetextstring = "jjfnj 948"
At the end I want to have:
echo $thetextstring; // should print jjf-nj948
So basically what am trying to do is to join the separated string then separate the first 3 letters with a -.
So far I have
$string = trim(preg_replace('/s+/', ' ', $thetextstring));
$result = explode(" ", $thetextstring);
$newstring = implode('', $result);
print_r($newstring);
I have been able to join the words, but how do I add the separator after the first 3 letters?
Use a regex with preg_replace function, this would be a one-liner:
^.{3}\K([^\s]*) *
Breakdown:
^ # Assert start of string
.{3} # Match 3 characters
\K # Reset match
([^\s]*) * # Capture everything up to space character(s) then try to match them
PHP code:
echo preg_replace('~^.{3}\K([^\s]*) *~', '-$1', 'jjfnj 948');
PHP live demo
Without knowing more about how your strings can vary, this is working solution for your task:
Pattern:
~([a-z]{2}) ~ // 2 letters (contained in capture group1) followed by a space
Replace:
-$1
Demo Link
Code: (Demo)
$thetextstring = "jjfnj 948";
echo preg_replace('~([a-z]{2}) ~','-$1',$thetextstring);
Output:
jjf-nj948
Note this pattern can easily be expanded to include characters beyond lowercase letters that precede the space. ~(\S{2}) ~
You can use str_replace to remove the unwanted space:
$newString = str_replace(' ', '', $thetextstring);
$newString:
jjfnj948
And then preg_replace to put in the dash:
$final = preg_replace('/^([a-z]{3})/', '\1-', $newString);
The meaning of this regex instruction is:
from the beginning of the line: ^
capture three a-z characters: ([a-z]{3})
replace this match with itself followed by a dash: \1-
$final:
jjf-nj948
$thetextstring = "jjfnj 948";
// replace all spaces with nothing
$thetextstring = str_replace(" ", "", $thetextstring);
// insert a dash after the third character
$thetextstring = substr_replace($thetextstring, "-", 3, 0);
echo $thetextstring;
This gives the requested jjf-nj948
You proceeding is correct. For the last step, which consists in inserting a - after the third character, you can use the substr_replace function as follows:
$thetextstring = 'jjfnj 948';
$string = trim(preg_replace('/\s+/', ' ', $thetextstring));
$result = explode(' ', $thetextstring);
$newstring = substr_replace(implode('', $result), '-', 3, false);
If you are confident enough that your string will always have the same format (characters followed by a whitespace followed by numbers), you can also reduce your computations and simplify your code as follows:
$thetextstring = 'jjfnj 948';
$newstring = substr_replace(str_replace(' ', '', $thetextstring), '-', 3, false);
Visit this link for a working demo.
Oldschool without regex
$test = "jjfnj 948";
$test = str_replace(" ", "", $test); // strip all spaces from string
echo substr($test, 0, 3)."-".substr($test, 3); // isolate first three chars, add hyphen, and concat all characters after the first three

How can I remove a specific format from string with RegEx?

I have a list of string like this
$16,500,000(#$2,500)
$34,000(#$11.00)
$214,000(#$18.00)
$12,684,000(#$3,800)
How can I extract all symbols and the (#$xxxx) from these strings so that they can be like
16500000
34000
214000
12684000
\(.*?\)|\$|,
Try this.Replace by empty string.See demo.
https://regex101.com/r/vD5iH9/42
$re = "/\\(.*?\\)|\\$|,/m";
$str = "\$16,500,000(#\$2,500)\n\$34,000(#\$11.00)\n\$214,000(#\$18.00)\n\$12,684,000(#\$3,800)";
$subst = "";
$result = preg_replace($re, $subst, $str);
To remove the end (#$xxxx) characters, you could use the regex:
\(\#\$.+\)
and replace it with nothing:
preg_replace("/\(\#\$.+\)/g"), "", $myStringToReplaceWith)
Make sure to use the g (global) modifier so the regex doesn't stop after it finds the first match.
Here's a breakdown of that regex:
\( matches the ( character literally
\# matches the # character literally
\$ matches the $ character literally
.+ matches any character 1 or more times
\) matches the ) character literally
Here's a live example on regex101.com
In order to remove all of these characters:
$ , ( ) # .
From a string, you could use the regex:
\$|\,|\(|\)|#|\.
Which will match all of the characters above.
The | character above is the regex or operator, effectively making it so
$ OR , OR ( OR ) OR # OR . will be matched.
Next, you could replace it with nothing using preg_replace, and with the g (global) modifier, which makes it so the regex doesn't return on the first match:
preg_replace("/\$|\,|\(|\)|#|\./g"), "", $myStringToReplaceWith)
Here's a live example on regex101.com
So in the end, your code could look like this:
$str = preg_replace("/\(\#\$.+\)/g"), "", $str)
$str = preg_replace("/\$|\,|\(|\)|#|\./g"), "", $str)
Although it isn't in one regex, it does not use any look-ahead, or look-behind (both of which are not bad, by the way).

Some confusion with preg_replace

I am very confused with preg_replace, I have this string and I would like to change ONLY the number before the _
$string = 'string/1_491107.jpg';
$newstring = preg_replace('#([0-9]+)_#', '666', $string);
But then I get "string/666491107.jpg" instead "string/666_491107.jpg"
Thanks
What you're doing here is matching the numbers in the parenthesis as $1 in your replacement. You don't actually say "only the stuff in parenthesises should be replaced".
You could do it like this:
$string = 'string/1_491107.jpg';
$newstring = preg_replace('#[0-9]+_#', '666_', $string);
or you could use a positive lookahead (only match a number sequence followed by an underscore, but don't include the underscore in the match):
$string = 'string/1_491107.jpg';
$newstring = preg_replace('#[0-9]+(?=_)#', '666', $string);
Regex 101 demo
You've got the underscore as part of the text to be replaced; so you also need to include it in the replacement:
$string = 'string/1_491107.jpg';
$newstring = preg_replace('#([0-9]+)_#', '666_', $string);

How to remove a string between the specific characters using regular expression in PHP?

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.

Strip phpbb bbcode

I want to display the most recent posts from my phpbb3 forum on my website, but without the bbcode.
so I'm trying to strip the bbcode but without succes
one of the posts for example could be:
[quote="SimonLeBon":3pwalcod]bladie bla bla[/quote:3pwalcod]bla bla bladie bla blaffsd
fsdjhgfd dgfgdffgdfg
to strip bbcodes i use the function i found via google, I've tried several other similiar functions aswell:
<?php
function stripBBCode($text_to_search) {
$pattern = '|[[\/\!]*?[^\[\]]*?]|si';
$replace = '';
return preg_replace($pattern, $replace, $text_to_search);
}
?>
This however doesn't really have any effect.
This will strip bbcode, that is valid (i.e. opening tags matching closing tags).
$str = preg_replace('/\[(\w+)=.*?:(.*?)\](.*?)\[\/\1:\2\]/', '$3', $str);
CodePad.
Reusable Function
function stripBBCode($str) {
return preg_replace('/\[(\w+)=.*?:(.*?)\](.*?)\[\/\1:\2\]/', '$3', $str);
}
Explanation
\[ match literal [.
(\w+) Match 1 or more word characters and save in capturing group 1.
= Match literal =.
.*? Match ungreedily every character except \n between = and :.
: Match literal :.
(.*?) Match ungreedily every character except \n between : and ] and save in capturing group 2.
\] Match literal ].
(.*?) Match ungreedily every character except \n between : and ] and save in capturing group 3.
\[ Match literal [.
/\1\2 Match previous capturing groups again.
\] Match literal ].
Here's the one from phpBB (slightly adjusted to be standalone):
/**
* Strips all bbcode from a text and returns the plain content
*/
function strip_bbcode(&$text, $uid = '')
{
if (!$uid)
{
$uid = '[0-9a-z]{5,}';
}
$text = preg_replace("#\[\/?[a-z0-9\*\+\-]+(?:=(?:".*"|[^\]]*))?(?::[a-z])?(\:$uid)\]#", ' ', $text);
$match = return array(
'#<!\-\- e \-\->.*?<!\-\- e \-\->#',
'#<!\-\- l \-\-><a (?:class="[\w-]+" )?href="(.*?)(?:(&|\?)sid=[0-9a-f]{32})?">.*?</a><!\-\- l \-\->#',
'#<!\-\- ([mw]) \-\-><a (?:class="[\w-]+" )?href="(.*?)">.*?</a><!\-\- \1 \-\->#',
'#<!\-\- s(.*?) \-\-><img src="\{SMILIES_PATH\}\/.*? \/><!\-\- s\1 \-\->#',
'#<!\-\- .*? \-\->#s',
'#<.*?>#s',
);
$replace = array('\1', '\1', '\2', '\1', '', '');
$text = preg_replace($match, $replace, $text);
}
Why don't you use the BBCode parsing facilities that are built in to PHP?
http://php.net/manual/en/book.bbcode.php
Nowadays, use phpbb's own function https://wiki.phpbb.com/Strip_bbcode

Categories