PHP preg_replace() pattern - php

I have about 500 lines stored in a text file.
Each line look like Filename_662344.xlsx , 324.
I would like to count numbers at the end of each line (324 in this case).
My idea is to delete part of lines using preg_replace() function.
I tried preg_replace("/[^0-9]/", '', $line); , but the result was 662344324
How should the pattern look like if I want to delete the filename (including numbers);
Thanks!

Can try this regex.
$line = 'Filename_662344.xlsx , 324';
$line = preg_replace("/^(.*?), /", '', $line);
echo $line;
Regex Demo

\d+$ will match the numbers at the end of a string
See Here for an example of it.
If you are trying to remove everything except the numbers, you can just use (^.*, ). This starts at the beginning of the line and select everything up to the comma. See Here for an example

Related

Remove '(' and text which follows from a string

Goal, to trim all text starting with the a left parenthesis '(' from a string. I've read through stack for the last hour, php.net, googled, I've tried using trim, ltrim, rtrim, strpos, preg_replace, etc. Everything that I have found so far has dealt with how to replace the text IF it is a know quantity - mine will vary.
Examples:
Text i want to keep (All of this i want to remove) as well as this...
Example 2:
Text 2 keep (text to remove 123)
Example 3:
Keep Please (123remove)
What is the best way to sanitize this string? The text which follows the first paren will be alphanumeric (letters, numbers, possibly even Exclamation points, etc). The only constant is the first paren '(', anything after i want to trim away/remove.
I am of novice level, I am not yet dealing with classes or jQuery, etc. I wish to do this on the server.
Thank you for any help or guidance.
You can use strpos to find the first parenthesis and substr to get the substring until this position :
$str = 'Test keep (remove) remove';
$pos = strpos($str, '(');
$newString = '';
if ($pos !== false) {
$newString = substr($str, 0, $pos);
}
echo $newString;
Output
Test keep
You were on the right track with preg_replace. You could try the following:
preg_replace('\([^]*', $replacement, $subject)
Tested and works
echo preg_replace('#\(.*#i','',$string_tostrip);
$str =" Text i want to keep (All of this i want to remove)";
$s=explode("(",$str);
$concatinated_str = $s[0];
echo $concatinated_str; // Text i want to keep

php preg_match() code for comma separated names

I need to validate input patterns using preg_match() so that the patterns is like " anyname1,anyname2,anyname3, ".
Note that there is a comma at the end too. Any letter or number is valid between the commas, numbers do not have to appear at the end. e.g "nam1e,Na2me,NNm22," is valid.
I tried ^([A-Za-z0-9] *, *)*[A-Za-z0-9]$ but did no work. I have gone through other posts too but did not get a perfect answer.
Can someone give me an answer for this?
If you just want the actual values without the comma, then you can simply use this:
\w+(?=[,])
http://regex101.com/r/xT6wE4/1
It sounds like you want to validate that the string contains a series of comma separated alpha-numeric substrings, with an optional trailing comma.
In that situation, this should achieve what you want.
$str = "anyname1,anyname2,anyname3,";
$re = '~^([a-z0-9]+,)+$~i';
if (preg_match($re, $str)) {
// String matches the pattern!
}
else {
// Nope!
}
If the value stored in $str contains a trailing space like in your example, and you don't want to use trim() on the value, the following regex will allow for whitespace at the end of $str:
~^([a-z0-9]+,)+\s*$~i
Why use such a complex solution for a simple problem? You can do the same in two steps:
1: trim spaces, line feeds, line returns and comma's:
$line = trim($line," \r\n,");
2: explode on comma's to see all the names:
$array = explode(',',$line);
You're not telling us what you're going to use it for, so I cannot know which format you really need. But my point is that you don't need complex string functions to do simple tasks.
^([a-zA-Z0-9]+,)+$
You can simply do this.See demo.
http://regex101.com/r/yR3mM3/8

How to remove every second occurrence within a string?

Basically, I have a string that I need to search through and remove every SECOND occurrence within it.
Here is what my string looks like ($s):
question1,answer1,answer2,answer3,answer4
question2,answer1,answer2,answer3,answer4
question3,answer1,answer2,answer3,answer4
Here is what my code currently looks like:
$toRemove = array("\n");
$finalString = str_replace($toRemove, "", $s);
As you can see, each line within my s string contains two \n between them. I would like to search through my string and only replace every SECOND \n so that my string ends up being:
question1,answer1,answer2,answer3,answer4
question2,answer1,answer2,answer3,answer4
question3,answer1,answer2,answer3,answer4
Is this possible? If so, how can I do it?
In your specific case, you may want to just replace two newlines with one newline:
$string = str_replace("\n\n", "\n", $string);
More complicated regex solutions could collapse any number of concurrent newlines:
preg_replace("/\n+/", "\n", "foo\n\nbar\n\n\n\n\nblee\nnope");
Adam's answer is correct for UNIX like systems but in Windows you can have different line endings. My Regex is a little bit rusty but I think this should work for UNIX and Windows.
$string = preg_replace('/[\n\r]{2}/', '\n', $string); Replace exact 2 line endings
$string = preg_replace('/[\n\r]+/', '\n', $string); Replace 1 or more line endings

PHP Regex: Select all except last occurrence

I'm trying to replace all \n's sans that final one with \n\t in order to nicely indent for a recursive function.
This
that
then
thar
these
them
should become:
This
that
then
thar
these
them
This is what I have: preg_replace('/\n(.+?)\n/','\n\t$1\n',$var);
It currently spits this out:
This
that
then
thar
these
them
Quick Overview:
Need to indent every line less the first and last line using regex, how can I accomplish this?
You can use a lookahead:
$var = preg_replace('/\n(?=.*?\n)/', "\n\t", $var);
See it working here: ideone
After fixing a quotes issue, your output is actually like this:
This
that
then
thar
these
them
Use a positive lookahead to stop that trailing \n from getting eaten by the search regex. Your "cursor" was already set beyond it so only every other line was being rewritten; your match "zones" overlapped.
echo preg_replace('/\n(.+?)(?=\n)/', "\n\t$1", $input);
// newline-^ ^-text ^-lookahead ^- replacement
Live demo.
preg_replace('/\n(.+?)(?=\n)/',"\n\t$1",$var);
Modified the second \n to be the lookahead (?=\n), otherwise you'd run into issues with regex not recognizing overlapping matches.
http://ideone.com/1JHGY
Let the downwoting begin, but why use regex for this?
<?php
$e = explode("\n",$oldstr);
$str = $e[count($e) - 1];
unset($e[count($e) - 1]);
$str = implode("\n\t",$e)."\n".$str;
echo $str;
?>
Actually, str_replace has a "count" parameter, but I just can't seem to get it to work with php 5.3.0 (found a bug report). This should work:
<?php
$count = substr_count($oldstr,"\n") - 1;
$newstr = str_replace("\n","\n\t",$oldstr,&$count);
?>

Regex to strip some lines out of a text file

I need to try and strip out lines in a text file that match a pattern something like this:
anything SEARCHTEXT;anything;anything
where SEARCHTEXT will always be a static value and each line ends with a line break. Any chance someone could help with the regext for this please? Or give me some ideas on where to start (been to many years since I looked at regex).
I am planning on using PHP's preg_replace() for this.
Thanks.
This solution removes all lines in $text which contain the sub-string SEARCHTEXT:
$text = preg_replace('/^.*?SEARCHTEXT.*\n?/m', '', $text);
My benchmark tests indicate that this solution is more than 10 times faster than '/\n?.*SEARCHTEXT.*$/m' (and this one correctly handles the case where the first line matches and the second one doesn't).
Use a regex to match the whole line like so:
^.*SEARCHTEXT.*$
preg_replace would be a good option for this.
$str = preg_replace('/\n?.*SEARCHTEXT.*$/m', '', $str);
The \n escape matches the line break for the matched line. This way matched lines are removed and the replace method does not just leave empty lines in the string.
The /m flag makes the caret (^) match the start of each line instead of the start of the string.

Categories