In PHP 5.3 there is a nice function that seems to do what I want:
strstr(input,"\n",true)
Unfortunately, the server runs PHP 5.2.17 and the optional third parameter of strstr is not available. Is there a way to achieve this in previous versions in one line?
For the relatively short texts, where lines could be delimited by either one ("\n") or two ("\r\n") characters, the one-liner could be like
$line = preg_split('#\r?\n#', $input, 2)[0];
for any sequence before the first line feed, even if it an empty string,
or
$line = preg_split('#\r?\n#', ltrim($input), 2)[0];
for the first non-empty string.
However, for the large texts it could cause memory issues, so in this case strtok mentioned below or a substr-based solution featured in the other answers should be preferred.
When this answer was first written, almost a decade ago, it featured a few subtle nuances
it was too localized, following the Opening Post with the assumption that the line delimiter is always a single "\n" character, which is not always the case. Using PHP_EOL is not the solution as we can be dealing with outside data, not affected by the local system settings
it was assumed that we need the first non-empty string
there was no way to use either explode() or preg_split() in one line, hence a trick with strtok() was proposed. However, shortly after, thanks to the Uniform Variable Syntax, proposed by Nikita Popov, it become possible to use one of these functions in a neat one-liner
but as this question gained some popularity, it's better to cover all the possible edge cases in the answer. But for the historical reasons here is the original solution:
$str = strtok($input, "\n");
that will return the first non-empty line from the text in the unix format.
However, given that the line delimiters could be different and the behavior of strtok() is not that straight, as "Delimiter characters at the start or end of the string are ignored", as it says the man page for the original strtok() function in C, now I would advise to use this function with caution.
It's late but you could use explode.
<?php
$lines=explode("\n", $string);
echo $lines['0'];
?>
$first_line = substr($fulltext, 0, strpos($fulltext, "\n"));
or something thereabouts would do the trick. Ugly, but workable.
try
substr( input, 0, strpos( input, "\n" ) )
echo str_replace(strstr($input, '\n'),'',$input);
list($line_1, $remaining) = explode("\n", $input, 2);
Makes it easy to get the top line and the content left behind if you wanted to repeat the operation. Otherwise use substr as suggested.
not dependent from type of linebreak symbol.
(($pos=strpos($text,"\n"))!==false) || ($pos=strpos($text,"\r"));
$firstline = substr($text,0,(int)$pos);
$firstline now contain first line from text or empty string, if no break symbols found (or break symbol is a first symbol in text).
try this:
substr($text, 0, strpos($text, chr(10)))
You can use strpos combined with substr. First you find the position where the character is located and then you return that part of the string.
$pos = strpos(input, "\n");
if ($pos !== false) {
echo substr($input, 0, $pos);
} else {
echo 'String not found';
}
Is this what you want ?
l.e.
Didn't notice the one line restriction, so this is not applicable the way it is. You can combine the two functions in just one line as others suggested or you can create a custom function that will be called in one line of code, as wanted. Your choice.
Many times string manipulation will face vars that start with a blank line, so don't forget to evaluate if you really want consider white lines at first and end of string, or trim it. Also, to avoid OS mistakes, use PHP_EOL used to find the newline character in a cross-platform-compatible way (When do I use the PHP constant "PHP_EOL"?).
$lines = explode(PHP_EOL, trim($string));
echo $lines[0];
A quick way to get first n lines of a string, as a string, while keeping the line breaks.
Example 6 first lines of $multilinetxt
echo join("\n",array_splice(explode("\n", $multilinetxt),0,6));
Can be quickly adapted to catch a particular block of text, example from line 10 to 13:
echo join("\n",array_splice(explode("\n", $multilinetxt),9,12));
Related
Let's say I have a string like:
Cant_Hold_Us_-_Fingerstyle_Guitar_0.mp3
How can I get rid of _0.mp3 dynamically with PHP? The values are not hard-coded for the current example. Maybe if i use explode?
$old = "your file name here";
$new = substr($old, 0, strrpos($old, "_"));
The substr method will take only the part of the string that you want.
The strrpos method finds the last index of the underscore and passes that number into the substr method so that it knows how far to cut. This method is ideal because rather than hardcoding a specific value, the script will dynamically change for each file, just as you suggested.
Just a bit of warning: if the file name does not contain an underscore, the method won't know where to cut to and will cause error in execution. A good bit of practice would be checking if (strrpos($old, "_") !== false).
I like Confiqure's answer. To complement, you could also use a regular expression if you find that you need more power.
$old = "Cant_Hold_Us_-_Fingerstyle_Guitar_0.mp3";
$new = preg_replace('/_\d+\.mp3$/', '', $old);
Regex is your friend. Have a look at preg_match and / or preg_replace.
$title = preg_replace("/_[0-9]+\.mp3$/i", "", $x);
Works for blablabla_21.mp3 as well....
this is a sentence oil on a line
this is another sentence
another one
hey oil sentence
I have these 4 sentences, what I want to do is to check if this sentence(each sentence is on a line) has the word oil. And if it does I would delete the whole sentence.
So I'll End up with this:
this is another sentence
another one
the lines including oil has been removed.
I had an idea of exploding these lines to an array. Then use foreach to check for oil. Deleting the element, then imploding.
But I was wondering if there are any faster ways?
You could use the strpos function. Here is a related question: How do I check if a string contains a specific word in PHP?.
While your idea with explode would work, there are easier ways. You can use strpos to find a substring within a string. If no substring is found it will return false. If you want case insensitivity you can for the original string to be all lowercase (or uppercase) with strtolower (or strtoupper ):
if( strpos(strtolower($string),'oil')!==false )
{
// string found
}
else
{
// string not found
}
use strpos() function in php, if that particular string has a position then that means that your string has that particular word or character.
Just have a look at a simple solution as per your requirement
foreach( explode($wholesentence,"\n" ) as $yourstrimg )
if (strpos($yourstrimg,'oil') !== false) {
echo 'oil';
}
}
Note:
"\n" is just used to indicate new line here, it can also be different line break operator change in different languages, like in html it is "<br />"
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
I have some code that searches a huge log file and finds a keyword, for the majority of cases this is near the bottom of the document. It would be more efficient in this case to start my search at the bottom and work my way up.
$pos = stripos($body,$keyword);
$snippet_pre = substr($body, $pos, SNIPPET_LENGTH);
I've looked at strripos and although it does what i want as in find the last occurrence it sounds like it searches from the beginning of the document so ill be adding a lot of unnecessary work to my query as most of the keywords are near the bottom of the string/document
Any ideas?
Explode your log file by linebreaks to get an array. Reverse your array, and now you can search line by line from the end.
$lines = explode("\n",$body);
$reversed = array_reverse($lines);
foreach($reversed AS $line) {
// Search for your keyword
}
If you are talking about a massive log file, such that you absolutely do not want to read it all into memory, you could also look at a reverse seek approach, though that's typically not needed. See here:
Read a file backwards line by line using fseek
strripos will start from the end and search backwards if you set a negative offset as the third parameter.
$pos = stripos($body,$keyword,$offset);
So I've seen a couple articles that go a little too deep, so I'm not sure what to remove from the regex statements they make.
I've basically got this
foo:bar all the way to anotherfoo:bar;seg98y34g.?sdebvw h segvu (anything goes really)
I need a PHP regex to remove EVERYTHING after the colon. the first part can be any length (but it never contains a colon. so in both cases above I'd end up with
foo and anotherfoo
after doing something like this horrendous example of psuedo-code
$string = 'foo:bar';
$newstring = regex_to_remove_everything_after_":"($string);
EDIT
after posting this, would an explode() work reliably enough? Something like
$pieces = explode(':', 'foo:bar')
$newstring = $pieces[0];
explode would do what you're asking for, but you can make it one step by using current.
$beforeColon = current(explode(':', $string));
I would not use a regex here (that involves some work behind the scenes for a relatively simple action), nor would I use strpos with substr (as that would, effectively, be traversing the string twice). Most importantly, this provides the person who reads the code with an immediate, "Ah, yes, that is what the author is trying to do!" instead of, "Wait, what is happening again?"
The only exception to that is if you happen to know that the string is excessively long: I would not explode a 1 Gb file. Instead:
$beforeColon = substr($string, 0, strpos($string,':'));
I also feel substr isn't quite as easy to read: in current(explode you can see the delimiter immediately with no extra function calls and there is only one incident of the variable (which makes it less prone to human errors). Basically I read current(explode as "I am taking the first incident of anything prior to this string" as opposed to substr, which is "I am getting a substring starting at the 0 position and continuing until this string."
Your explode solution does the trick. If you really want to use regexes for some reason, you could simply do this:
$newstring = preg_replace("/(.*?):(.*)/", "$1", $string);
A bit more succinct than other examples:
current(explode(':', $string));
You can use RegEx that m.buettner wrote, but his example returns everything BEFORE ':', if you want everything after ':' just use $2 instead of $1:
$newstring = preg_replace("/(.*?):(.*)/", "$2", $string);
You could use something like the following. demo: http://codepad.org/bUXKN4el
<?php
$s = 'anotherfoo:bar;seg98y34g.?sdebvw h segvu';
$result = array_shift(explode(':', $s));
echo $result;
?>
Why do you want to use a regex?
list($beforeColon) = explode(':', $string);