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
Related
I'm trying to sorround all numbers in a string (numbers that are followed by % sign) in span tags
Here are some regex noob attempts at solving it:
$str = preg_replace("/(1-9+)%/", "<span>$1</span>", $str);
or
$str = preg_replace("/([1-9]+)%/", "<span>$1</span>", $str);
Nothing is replaced
I bet I have got it all wrong.. I need to learn regex more, I know
But can you help me further with this?
Your regex is almost correct but there is one crucial glitch. You are matching [1-9] instead of [0-9].
EDIT: Use of preg_replace_callback to generate random number:
Following should work:
echo preg_replace_callback('/([0-9]+)%/', function ($m) {
return '<span>' . rand($m[1]-5, $m[1]+5) . '%</span>'; }, 'hello 100% hello');
After trying some more, this works:
$str = preg_replace('/[0-9]{1,3}%/', '<span>$0</span>', $str);
Using () was first mistake. Using 1-9 instead of 0-9 was other mistake. Using $1 instead of $0 was third mistake (I think)
I am attempting to change a string occurance e.g. http://www.bbc.co.uk/ so that it appears inside a html link e.g. http://www.bbc.co.uk
however for some reason my regex conversion does not work. Can someone please point me in the correct direction?
$text = "I love this website http://www.bbc.co.uk/";
$x = preg_replace("#[a-z]+://[^<>\s]+[[a-z0-9]/]#i", "\\0", $text);
var_dump($x);
outputs I love this website http://www.bbc.co.uk/ (No html link)
Your weird character class is at fault:
[[a-z0-9]/]
Double square brackets are for POSIX character classes like [[:digit:]].
You meant to write just:
[a-z0-9/]
It is because you regex is giving you a match (in fact it's really not even close to giving you a match as you are not accepting periods in the domain name at all). Try something like this:
$pattern = '#https?://.*\b#i';
$replace = '$0';
$x = preg_replace($pattern, $replace, $text);
Note that I am not actually trying to validate the URL format here, so I just accept anything like http():// up to the next word boundary. It didn't seem as if you were going for a true URL validation regex anyway (i.e. validating there is at least one ., that the TLD component has 2-6 characters, etc.), so I just figure I would give you the simplest pattern that would match.
Use this:
$x = preg_replace('#http://[?=&a-z0-9._/-]+#i', '<a target="_blank" href="$0">$0</a>', $text);
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);
I know this type of question has been asked and answered before but I cant isolate the error in my pattern match.
due to some very screwy legacy db input I am trying to remove anything between two html special chars and then will move on to process the remains after.
the original code went 1<b>2 to bold anything after 1, but has ended up as 1<b>2
I would like to be left with either 1<>2 or 1 2
am I even close?
thx
Art
$str = '1<b>2';
$output = preg_replace('/&#?[a-z0-9]{2,8};(.*?)\/&#?[a-z0-9]{2,8};/is', '',$str);
Looks like you should remove the slash in the middle
/&#?[a-z0-9]{2,8};[^&]+&#?[a-z0-9]{2,8};/is
Have you tried to do:
$str = strip_tags(html_entity_decode('1<b>2'));
or if you want to replaces tags with something else, like an space:
$str = html_entity_decode('1<b>2');
$output = preg_replace('/<\/?[^\>]+>/ui', ' ',$str);
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));