PHP remove specific character and number from beginning of string - php

I want to remove brackets and number from beginning of string but problem is brackets and number is coming only specific string not all.
for example following is my string.
1) [4] Mustangs 8u
2) Pool a First Place
3) Team slect
4) [3] In pruduct
so above you can see only 1 and 4 string have number with brackets at beginning of string so i want to only remove that if that found in string.
I write following code but is not work.
<?php
foreach ($grouped as $round_number => $group) {
$team_1_name = $group->team_1_name;
$new_str = preg_replace('/^([0-9]* \w+ )?(.*)$/', '$2', $team_1_name);
$date = date ('F d, Y g:iA', $unix_time);
}
?>

Try regular expression /^(\[[0-9]\]?\s?)/ as:
$new_str = preg_replace('/^(\[[0-9]\]?\s?)/', '$2', $team_1_name);
For reference: regexr

In case your numbers are multi digit (i.e. '[11] In pruduct')...
echo preg_replace('/^(\[\d*\]?\s?)/', '$2', $team_1_name);

Instead regex you can use ltrim() with a character mask. If your strings never start with a number:
$new_str = ltrim($team_1_name, "0123456789[] ");
else you could check if the first char is a bracket:
$new_str = $team_1_name[0] == '[' ? ltrim($team_1_name, '0123456789[] ') : '';

Related

Ignore character using regex (pcre) PHP

I am trying to capture date from a file file-2018-02-19-second.json.
I am using .*file-(..........).*.json regex to capture the date in the file .The regex is capturing 2018-02-19 date in the file but I want to ignore "-" in the file and only capture 20180219. How can I do it?
If your filenames have always the same format, you can convert your string to a DateTime instance using DateTime::createFromFormat:
$date = DateTime::createFromFormat('*-Y-m-d-*.*', 'file-2018-02-19-second.json');
echo $date->format('Ymd');
You can find the different format characters and their meanings in the php manual.
$fileName = 'file-2018-02-19-second.json';
preg_match('#([12]\d{3}-(0[1-9]|1[0-2])-(0[1-9]|[12]\d|3[01]))#is', $fileName,
$output);
if (!empty($output)) {
$date = preg_replace('#-#is', '', $output[1]);
echo $date;
}
hope can help you!
related link: https://www.regextester.com/96683
Option 1 - Match & Replace
See code in use here
<?php
$fn = 'file-2018-02-1-second.json';
$fn = preg_match('/.*file-\K\d{4}-\d{2}-\d{2}/', $fn, $o);
echo isset($o[0]) ? preg_replace('/\D+/', '', $o[0]) : 'No match found';
Option 2 - Group & Concatenate
See code in use here
<?php
$fn = 'file-2018-02-1-second.json';
$fn = preg_match('/.*file-(\d{4})-(\d{2})-(\d{2})/', $fn, $o);
echo isset($o[1], $o[2], $o[3]) ? $o[1].$o[2].$o[3] : 'No match found';
Explanation of Patterns
.*file-\K\d{4}-\d{2}-\d{2}
.* Match any character any number of times
file- Match this literally
\K Resets the starting point of the match. Any previously consumed characters are no longer included in the final match.
\d{4} Match any digit exactly 4 times
- Match this literally
\d{2} Match any digit exactly 2 times
- Match this literally
\d{2} Match any digit exactly 2 times
The second pattern \D+ simply matches any non-digit character one or more times for replacement.
The last pattern (from option 2) is really just the simplified version of the first pattern I described, but groups each number part into capture groups.
Result: 20180219
This question appears to be solely about data extract, not about data validation.
Code: (Demo)
$file = 'file-2018-02-19-second.json';
$date = preg_replace('~\D+~', '', $file);
echo $date;
Output:
20180219
If you need slightly more accuracy/validation than that (leveraging the location of file-, you can use \G to extract the date components before imploding them.
Code: (Demo) (Pattern Demo)
$file = 'somefile-2018-02-19-second.json';
echo preg_match_all('~\Gfile-\K\d+|-\K\d+~', $file, $out) ? implode($out[0]) : 'fail';
// same result as earlier method

Regex rules in an array

Maybe it can not be solved this issue as I want, but maybe you can help me guys.
I have a lot of malformed words in the name of my products.
Some of them has leading ( and trailing ) or maybe one of these, it is same for / and " signs.
What I do is that I am explode the name of the product by spaces, and examines these words.
So I want to replace them to nothing. But, a hard drive could be 40GB ATA 3.5" hard drive. I need to process all the word, but I can not use the same method for 3.5" as for () or // because this 3.5" is valid.
So I only need to replace the quotes, when it is at the start of the string AND at end of the string.
$cases = [
'(testone)',
'(testtwo',
'testthree)',
'/otherone/',
'/othertwo',
'otherthree/',
'"anotherone',
'anothertwo"',
'"anotherthree"',
];
$patterns = [
'/^\(/',
'/\)$/',
'~^/~',
'~/$~',
//Here is what I can not imagine, how to add the rule for `"`
];
$result = preg_replace($patterns, '', $cases);
This is works well, but can it be done in one regex_replace()? If yes, somebody can help me out the pattern(s) for the quotes?
Result for quotes should be this:
'"anotherone', //no quote at end leave the leading
'anothertwo"', //no quote at start leave the trailin
'anotherthree', //there are quotes on start and end so remove them.
You may use another approach: rather than define an array of patterns, use one single alternation based regex:
preg_replace('~^[(/]|[/)]$|^"(.*)"$~s', '$1', $s)
See the regex demo
Details:
^[(/] - a literal ( or / at the start of the string
| - or
[/)]$ - a literal ) or / at the end of the string
| - or
^"(.*)"$ - a " at the start of the string, then any 0+ characters (due to /s option, the . matches a linebreak sequence, too) that are captured into Group 1, and " at the end of the string.
The replacement pattern is $1 that is empty when the first 2 alternatives are matched, and contains Group 1 value if the 3rd alternative is matched.
Note: In case you need to replace until no match is found, use a preg_match with preg_replace together (see demo):
$s = '"/some text/"';
$re = '~^[(/]|[/)]$|^"(.*)"$~s';
$tmp = '';
while (preg_match($re, $s) && $tmp != $s) {
$tmp = $s;
$s = preg_replace($re, '$1', $s);
}
echo $s;
This works
preg_replace([[/(]?(.+)[/)]?|/\"(.+)\"/], '$1', $string)

php regex replace each character with asterisk

I am trying to something like this.
Hiding users except for first 3 characters.
EX)
apple -> app**
google -> goo***
abc12345 ->abc*****
I am currently using php like this:
$string = "abcd1234";
$regex = '/(?<=^(.{3}))(.*)$/';
$replacement = '*';
$changed = preg_replace($regex,$replacement,$string);
echo $changed;
and the result be like:
abc*
But I want to make a replacement to every single character except for first 3 - like:
abc*****
How should I do?
Don't use regex, use substr_replace:
$var = "abcdef";
$charToKeep = 3;
echo strlen($var) > $charToKeep ? substr_replace($var, str_repeat ( '*' , strlen($var) - $charToKeep), $charToKeep) : $var;
Keep in mind that regex are good for matching patterns in string, but there is a lot of functions already designed for string manipulation.
Will output:
abc***
Try this function. You can specify how much chars should be visible and which character should be used as mask:
$string = "abcd1234";
echo hideCharacters($string, 3, "*");
function hideCharacters($string, $visibleCharactersCount, $mask)
{
if(strlen($string) < $visibleCharactersCount)
return $string;
$part = substr($string, 0, $visibleCharactersCount);
return str_pad($part, strlen($string), $mask, STR_PAD_RIGHT);
}
Output:
abc*****
Your regex matches all symbols after the first 3, thus, you replace them with a one hard-coded *.
You can use
'~(^.{3}|(?!^)\G)\K.~'
And replace with *. See the regex demo
This regex matches the first 3 characters (with ^.{3}) or the end of the previous successful match or start of the string (with (?!^)\G), and then omits the characters matched from the match value (with \K) and matches any character but a newline with ..
See IDEONE demo
$re = '~(^.{3}|(?!^)\G)\K.~';
$strs = array("aa","apple", "google", "abc12345", "asdddd");
foreach ($strs as $s) {
$result = preg_replace($re, "*", $s);
echo $result . PHP_EOL;
}
Another possible solution is to concatenate the first three characters with a string of * repeated the correct number of times:
$text = substr($string, 0, 3).str_repeat('*', max(0, strlen($string) - 3));
The usage of max() is needed to avoid str_repeat() issue a warning when it receives a negative argument. This situation happens when the length of $string is less than 3.

PHP str_replace can't give me the output I want

I want to replace a string at a particular position. For that I used str_replace() PHP function, but after that, I can't get an output. Here I show you what I want.
$str = "hello 8-7-2015 world -12";
// here I want replace - with ' desh ' but in date only. That I have detected using check before character if space than it should be 'minus' otherwise it should be 'desh'.
$key = strpos($str, "-");
if($key !== false){
$a = substr($str, $key-1 , 1);
if($a != " "){
$str = str_replace("-","desh",$str);
}else{
$str = str_replace("-","minus",$str);
}
}
I get output like: hello 8 desh 7 desh 2015 world desh 12 . Everywhere there is desh I want minus 12. Other values are okay and should not be changed.
Means particular position change.
Your code (with an if) doesn't loop over the string looking for all occurrences, so that should have raised an alert flag with you when all the occurrences were changed.
What it does is to find the first occurrence, which isn't preceded by a space, then it executes:
str_replace("-","desh",$str);
which replaces all occurrences within the string. In order to do what you want, all you need is:
str_replace(" -"," minus",$str);
str_replace("-","desh",$str);
This will first take care of all - character preceded by a space, turning them into " minus".
The second line will then take care of all the remaining - characters, replacing them with "desh".
Just as an aside, if you're doing this to be able to "speak" the words (in the sense of a text-to-speech (TTS) program), you probably want spaces on either sides of the words you're adding. You can achieve that with a very small modification:
str_replace(" -"," minus ",$str);
str_replace("-"," desh ",$str);
That may make it easier for your TTS code to handle the words.
There's no point in your condition since str_replace takes effect on whole the string without any relation to your $key variable.
$str = str_replace(" -","minus",$str);
$str = str_replace("-","desh",$str);
Truth is that you don't even need that condition. Simply use the first str_replace when the search term has blank space prior to it and the second str_replce doesn't. (order it's important).
You can use regex:
$str = preg_replace(
['/(\d{1,2})-(\d{1,2})-(\d{2,4})/','/-(\d+)/'],
['$1 desh $2 desh $3', 'minus $1'],
$str);
check this,
First you have to get the date from the string, then change the date format as you want after that concatenate with other strings
$str = explode(' ',$str);
$str1 = str_replace("-","desh",$str[1]);
$str2 = str_replace("-","minus",$str[2]);
$str = $str[0].$str1.$str2;

Removing all characters and numbers except last variable with dash symbol

Hi I want to remove a characters using preg_replace in php so i have this code here which i want to remove the whole characters, letters and numbers except the last digit(s) which has dash(-) symbol followed by a digits so here's my code.
echo preg_replace('/(.+)(?=-[0-9])|(.+)/','','asdf1245-10');
I expect the result will be
-10
the problem is above is not working very well. I checked the pattern using http://www.regextester.com/ it seems like it works, but on the other side http://www.phpliveregex.com/ doesn't work at all. I don't know why but anyone who can help to to figure it out?
Thanks a lot
Here is a way to go:
echo preg_replace('/^.+?(-[0-9]+)?$/','$1','asdf1245-10');
Output:
-10
and
echo preg_replace('/^.+?(-[0-9]+)?$/','$1','asdf124510');
Output:
<nothing>
My first thinking is to use explode in this case.. make it simple like the following code.
$string = 'asdf1245-10';
$array = explode('-', $string);
end($array);
$key = key($array);
$result = '-' . $array[$key];
$result => '-10';
An other way:
$result = preg_match('~\A.*\K-\d+\z~', $str, $m) ? $m[0] : '';
pattern details:
\A # start of the string anchor
.* # zero or more characters
\K # discard all on the left from match result
-\d+ # the dash and the digits
\z # end of the string anchor
echo preg_replace('/(\w+)(-\w+)/','$2', 'asdf1245-10');

Categories