I have an array with values like
$arr = array("abc-xyz","a pqr","rty'gjg","sdhf,sjh","dhd.jkyt");
I want to replace all the occurrences of hyphen, space, comma, dot, single quotes with underscore.
How can I do a replace with pattern.
I know I have to use
preg_replace($pattern,$replacewith,$string);
But I dont know how to use it.
Hope this simple preg_replace will help you out.
Regex: [\'\.,\s-]
1. [\'\.,\s-] this will match either of these characters , ,-,., ' or space
Try this code snippet here
<?php
ini_set('display_errors', 1);
$arr = array("abc-xyz","a pqr","rty'gjg","sdhf,sjh","dhd.jkyt");
$arr=preg_replace('/[\'\.,\s-]/', "_", $arr);
print_r($arr);
Related
I have a load of labels which are camel case. Some examples are
whatData
whoData
deliveryDate
importantQuestions
What I am trying to do is this. Any label which has the word Data needs to have this word removed. At the point of the capital letter, I need to provide a space. Finally, everything should be uppercase. I have done the removal of Data and the uppercase by doing this ($data->key is the label)
strtoupper(str_replace('Data', '', $data->key))
The part I am struggling with is adding the spaces between words. So basically the above words should end up like this
WHAT
WHO
DELIVERY DATE
IMPORTANT QUESTIONS
How can I factor in the last part of this?
Thanks
It will add spaces before every capital letters. Try this:
$String = 'whatData';
$Words = preg_replace('/(?<!\ )[A-Z]/', ' $0', $String);
Problem
Your regex '~^[A-Z]~' will match only the first capital letter. Check out Meta Characters in the Pattern Syntax for more information.
Your replacement is a newline character '\n' and not a space.
Solution
Use preg_replace(). Try below code.
$string = "whatData";
echo preg_replace('/(?<!\ )[A-Z]/', ' $0', $string);
Output
what Data
Try following:
$string = 'importantQuestions';
$string = strtoupper(ltrim(preg_replace('/[A-Z]/', ' $0', $string)));
echo $string;
This will give you output as:
IMPORTANT QUESTIONS
Try this:
preg_split: split on camel case
array_map: UPPER case all the element
implode: Implode the array
str_replace: Replace the `DATE` with empty
trim: trim the white spaces.
Do this simple things:
echo trim(str_replace("DATE", "", implode(" ", array_map("strtoupper", preg_split('/(?=[A-Z])/', 'deliveryDate', -1, PREG_SPLIT_NO_EMPTY))))); // DELIVERY
This is result exactly what you want.
I am using preg_replace() and a regular expression to remove all characters before a hyphen (-). I'd like to update the expression to also remove the hyphen itself. The full line of code is shown below in context.
$item['options']['Size'] = preg_replace('/^[^-]*/', '', $item['options']['Size']);
So as it stands let's say I have the below string:
TEST123-150X200
The current preg_replace function will leave me with:
-150X200
I'd like to end up with:
150X200
Could anyone suggest how I can update the regular_expression to achieve this. Thanks
You can add a hyphen at the end of the pattern.
$item['options']['Size'] = preg_replace('/^[^-]*-/', '', $item['options']['Size']);
^
This way, the hyphen is matched (=consumed) and will be removed. Note that [^-] is a negated character class that matches any character but a -. Thus the hyphen was not matched by your original regex.
A non-regex approach:
$item['options']['Size'] = ltrim(strstr($item['options']['Size'], '-'),'-');
See IDEONE demo
<?php
$item = 'TEST123-150X200'; // string here
echo preg_replace('/^[^-]*-/', '', $item);
?>
In addition to the answers/comments given, you could also use a positive lookbehind and replace this:
<?php
$str = "TEST123-150X200";
$regex = '/.*(?<=-)/i';
$item['options']['Size'] = preg_replace($regex, '', $str);
// output: 150X200
?>
Alternatively (as described in the comment), start counting from 1:
$item['options']['Size'] = substr(preg_replace('/^[^-]*/', '', $item['options']['Size']), 1);
I dont think it needs a regex for this...
$str = "TEST123-150X200";
var_dump(end(explode("-", $str))); //string(7) "150X200"
var_dump(ltrim(strstr($str, "-"), "-"));//string(7) "150X200"
var_dump(substr(strrchr($str, "-"), 1) );//string(7) "150X200"
I couldn't find the solution using search.
I am looking for a php solution to remove all character BEFORE the second occurance of and underscore (including the underscore)
For example:
this_is_a_test
Should output as:
a_test
I currently have this code but it will remove everything after the first occurance:
preg_replace('/^[^_]*.s*/', '$1', 'this_is_a_test');
Using a slightly different approach,
$s='this_is_a_test';
echo implode('_', array_slice( explode( '_', $s ),2 ) );
/* outputs */
a_test
preg_replace('/^.*_.*_(.*)$/U', '$1', 'this_is_a_test');
Note the U modifier which tells regex to take as less characters for .* as possible.
You can also use explode, implode along with array_splice like as
$str = "this_is_a_test";
echo implode('_',array_splice(explode('_',$str),2));//a_test
Demo
Why go the complicated way? This is a suggestion though using strrpos and substr:
<?php
$str = "this_is_a_test";
$str_pos = strrpos($str, "_");
echo substr($str, $str_pos-1);
?>
Try this one.
<?php
$string = 'this_is_a_test';
$explode = explode('_', $string, 3);
echo $explode[2];
?>
Demo
I'm still in favor of a regular expression in this case:
preg_replace('/^.*?_.*?_/', '', 'this_is_a_test');
Or (which looks more complex here but is easily adjustable to N..M underscores):
preg_replace('/^(?:.*?_){2}/', '', 'this_is_a_test');
The use of the question mark in .*? makes the match non-greedy; and the pattern has been expanded from the original post to "match up through" the second underscore.
Since the goal is to remove text the matched portion is simply replaced with an empty string - there is no need for a capture group or to use such as the replacement value.
If the input doesn't include two underscores then nothing is removed; such can be adjusted, very easily with the second regular expression, if the rules are further clarified.
I'm trying to remove all words of less than 3 characters from a string, specifically with RegEx.
The following doesn't work because it is looking for double spaces. I suppose I could convert all spaces to double spaces beforehand and then convert them back after, but that doesn't seem very efficient. Any ideas?
$text='an of and then some an ee halved or or whenever';
$text=preg_replace('# [a-z]{1,2} #',' ',' '.$text.' ');
echo trim($text);
Removing the Short Words
You can use this:
$replaced = preg_replace('~\b[a-z]{1,2}\b\~', '', $yourstring);
In the demo, see the substitutions at the bottom.
Explanation
\b is a word boundary that matches a position where one side is a letter, and the other side is not a letter (for instance a space character, or the beginning of the string)
[a-z]{1,2} matches one or two letters
\b another word boundary
Replace with the empty string.
Option 2: Also Remove Trailing Spaces
If you also want to remove the spaces after the words, we can add \s* at the end of the regex:
$replaced = preg_replace('~\b[a-z]{1,2}\b\s*~', '', $yourstring);
Reference
Word Boundaries
You can use the word boundary tag: \b:
Replace: \b[a-z]{1,2}\b with ''
Use this
preg_replace('/(\b.{1,2}\s)/','',$your_string);
As some solutions worked here, they had a problem with my language's "multichar characters", such as "ch". A simple explode and implode worked for me.
$maxWordLength = 3;
$string = "my super string";
$exploded = explode(" ", $string);
foreach($exploded as $key => $word) {
if(mb_strlen($word) < $maxWordLength) unset($exploded[$key]);
}
$string = implode(" ", $exploded);
echo $string;
// outputs "super string"
To me, it seems that this hack works fine with most PHP versions:
$string2 = preg_replace("/~\b[a-zA-Z0-9]{1,2}\b\~/i", "", trim($string1));
Where [a-zA-Z0-9] are the accepted Char/Number range.
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.