How to do a regex replacement, adding characters in a date string? - php

For PHP
I have a date I want line wrapped.
I have $date = '2008-09-28 9:19 pm';
I need the first space replaced with a br
to become
2008-09-28<br>9:19 pm
If it wasn't for that second space before PM, I would just str_replace() it.

$date = preg_replace('/ /', '<br>', $date, 1);

s/ /<br\/>/ should do it. Though PHP regex might be greedy and replace all spaces.
edit
I support Ben Hoffstein's PHP solution. Where possible, avoid regex as it nearly always has unintended side effects.

$date = '2008-09-28 9:19 pm';
$result = preg_replace('/(\d{4}-\d{2}-\d{2}) (.*)/', '$1<br>$2', $date);

If you want a regex to match the pattern and return both parts, you can use the following. However, considering all that you're doing is replacing only 1 space, try the str_replace_once that I'll suggest after the regex. Regex is for complicated parsing instead of a wasteful use like replacing one space (no offense intended).
Please note that the following is browser-code, so don't attempt to use it verbatim. Just in case of a typo.
$regex = '/([\d]{4}-[\d]{2}-[\d]{2}) ([\d]{1,2}:[\d]{2} (am|pm))/';
$match = preg_match($regex, '2008-09-28 9:19 pm');
print $match[1]; // Returns 2008-09-28
print $match[2]; // Returns 9:19 pm
// Or replace:
preg_replace($regex, '$1<br>$2', $date);
I suggest the following, much faster mechanism. See this post for the function str_replace_once().
str_replace_once(' ', '<br>', $date);

The other way to do this, which is faster but a bit more code, is
$date = substr($date, 0, 10) . '<br>' . substr($date, 11);

Related

Replace certain group by certain string

I want to replace a string by different patterns depending on it format. For example:
The pattern Y-m-d should be replaced by \d{4}-\d{2}-\d{2},
m-d-Y should be \d{2}-\d{2}-\d{4} and so on.
I used preg_replace() two times for doing it. One for replacing \m|d\ and another for \Y\.
$pattern = preg_replace("/m|d/", "\d{2}", $format);
$pattern = preg_replace("/Y/", "\d{4}", $pattern);
I want to know how can I do it by singe regex. Your help will be appreciated.
Thanks
preg_replace can act on array:
$pat = array('/m/', '/d/', '/Y/');
$repl = array('\\d{2}', '\\d{2}', '\\d{4}');
$pattern = preg_replace($pat, $repl, $pattern);

PHP trim and return a string from its right

I'm trying to take a string that's output from MySql like this (MySql outputs X characters):
$str = 'Buddy you're a boy make a big noise Playin in the stre';
and trying to start from the right side, trim whatever is there up till the first space. Sounded simple when I got down to it, but now, it has my brain and fingers in knots.
The output I'm tying to achieve is simple:
$str = 'Buddy you're a boy make a big noise Playin in the';
Notice, that characters starting from the right, till the first space, are removed.
Can you help?
My Fiddle
$str = 'Buddy you\'re a boy make a big noise Playin in the stre';
//echo rtrim($str,' ');
It's a useful idiom to remember on its own: to remove all the characters preceding a specific one from the right side of the string (including that special character), use the following:
$trimmed = substr($str, 0, strrpos($str, ' '));
... where ' ' is that special character.
Demo
If you don't know, however, whether or not the character is present, you'd check the result of sttrrpos first:
$last_space_index = strrpos($str, ' ');
$trimmed = $last_space_index !== false
? substr($str, 0, $last_space_index)
: $str;
And if there can be more than one character that you need to trim, like in 'hello there test' line, just rtrim the result:
$trimmed = rtrim(substr($str, 0, strrpos($str, ' ')), ' ');
In this case, however, a regex-based solution looks more appropriate:
$trimmed = preg_replace('/ +[^ ]*$/', '', $str);
I think your best option would be a regex replace:
preg_replace('/\s+\S*$/', '', $str);
which outputs Buddy you're a boy make a big noise Playin in the
And the Fiddle
it's probably easier to do it with regex, but I'm sooo bad with that! You shoud try this:
// Get all the words in an array
$strArray = explode(" ", $str);
// Remove the last word.
array_pop($strArray);
// Get it back into a sentence
$newString = implode(" ", $strArray);
There's a hundred ways to do this, here are some options:
array_pop'ing the last word off an array we create from explode:
$arr = explode(" ", $str);
$fixed_arr = array_pop($arr);
$result = implode(" ", $arr);
Using regular expressions:
$result = preg_replace('/\s+\S*$/', '', $str);
and using strrpos and substr:
$spacePos = strrpos($str, ' ');
$result = substr($str, 0, $spacePos);
In mysql use
left(field,length)
to output only the strlen first digits
right(field,length) having opposite effects
otherwise use substr($string,0,$length) or regex in php
As a matter of regex performance comparison, the regex engine can move faster through the string when it can perform greedy matching with minimal backtracking.
/ +[^ ]*$/ uses 68 steps. (#raina77ow)
/(?:[^ ]+\K )+.*/ uses 56 steps. (#mickmackusa)
/(?:\K [^ ]*)+/ uses 48 steps. (#mickmackusa)
\s+\S*$ uses 34 steps. (#ChrisBornhoft and #RyanKempt)
/.*\K .*/ uses just 15 steps. (#mickmackusa)
Based on these comparisons, I recommend greedily matching any characters, then restarting the fullstring match before matching the last occurring space, then matching zero or more characters until the end of the string.
Code: (Demo)
$string = "Buddy you're a boy make a big noise Playin in the stre";
var_export(
preg_replace('/.*\K .*/', '', $string)
);
Output:
'Buddy you\'re a boy make a big noise Playin in the'

php string replace/remove

Say I have strings: "Sports Car (45%)", or "Truck (50%)", how can I convert them to "Sports_Car" and "Truck".
I know about str_replace or whatever but how do I clip the brackets and numbers part off the end? That's the part I'm struggling with.
You can do:
$s = "Sports Car (45%)";
$s = preg_replace(array('/\([^)]*\)/','/^\s*|\s*$/','/ /'),array('','','_'),$s);
See it
There are a few options here, but I would do one of these:
// str_replace() the spaces to _, and rtrim() numbers/percents/brackets/spaces/underscores
$result = str_replace(' ','_',rtrim($str,'01234567890%() _'));
or
// Split by spaces, remove the last element and join by underscores
$split = explode(' ',$str);
array_pop($split);
$result = implode('_',$split);
or you could use one of a thousand regular expression approaches, as suggested by the other answers.
Deciding which approach to use depends on exactly how your strings are formatted, and how sure you are that the format will always remain the same. The regex approach is potentially more complicated but could afford finer-grained control in the long term.
A simple regex should be able to achieve that:
$str = preg_replace('#\([0-9]+%\)#', '', $str);
Of course, you could also choose to use strstr() to look for the (
You can do that using explode:
<?php
$string = "Sports Car (45%)";
$arr = explode(" (",$string);
$answer = $arr[0];
echo $answer;
?>

php remove everything in the string, keep the last digits

I have values like below:
$var1 = car-123-244343
$var2 = boat-2-1
$var3 = plane-311-23
I need to remove everything and keep the last digit/ditgits after the second hyphen
Expecting values:
244343
1
23
This is what I've got
$stripped = preg_replace('^[a-z]+[-]$', '', 'car-123-244343');
I got a big red error No ending delimiter '^' found
Without regex:
$var1 = substr($var1, strrpos($var1, '-') + 1);
What this does is the same as:
$pos = strrpos($var1, '-') + 1 takes the last postion of '-' and adds 1 for starting at the next character
substr($var, $pos) takes the $var and returns the substring starting in $pos.
I think is less expensive than using regex.
Edit:
As pointed below by konforce, if you are not sure which all the strings have that format, you have to verify it.
this function will work:
function foo($value)
{
$split = explode('-', $value);
return $split[count($split)-1];
}
Here is a fun version with explode:
list($vehicle, $no1, $no2) = explode('-', $data);
First, that error means your regex needs to be enclosed in delimiters (below I use the classic /).
Second, I would rewrite your regex to this:
$stripped = preg_replace('/.+?(\d+)$/', '$1', 'car-123-244343');
If you can operate on the assumption that what comes after the last - is always a number, the other solutions also work.
With regex:
$endnumber = preg_replace('/.*[^0-9]/', '', $input);
Remove everything up till, and including, the last non-digit.

Need to insert - into a variable holding a date?

I have a date variable with the format
2008 12 29
to have it correctly display from within my database app I need the format to be
2008-12-29
Is there a way to simply add the - into the string or replace the spaces with -?
I am using PHP and the date is stored in $release_date
Use str_replace():
$release_date = str_replace(' ', '-', $release_date);
The str_replace() method is what you search for:
$good_format_date = str_replace(' ', '-', $date);
If you know for a fact that the spaces will always be standard (spacebar) spaces, use str_replace() as BoltClock said.
However, if it's possible that there may be extra spaces, tabs, or other whitespace characters in between your date parts, use preg_replace() as it will work in almost all cases unlike str_replace():
$release_date = preg_replace( '/\s+/', '-', $release_date );

Categories