PHP Regex Replace Two Slashes (//) to New Line - php

What I'm trying to do here is take a string that might have what would normally be a code comment, and replace that with something else, especially wrapping it in something else. I'm pretty sure the preg_replace function would work here, but I don't have an idea on where to start with the Regex. For example:
Hello world //this is a comment
Testing //not testing
Test again
Would turn into
Hello world %//this is a comment%
Testing %//not testing%
Test again
preg_replace('???', '%$1%', $matches); is as much as I can figure out on my own, any help is much appreciated!

preg_replace('~//.*$~m', '', $str);
This will remove everything after (and including) // to the end of the line
http://ideone.com/Xhmpd
preg_replace('~//.*$~m', 'foo \\0 bar', $str);
This will wrap them with foo bar around
http://ideone.com/IqkWM

Try this:
$string = "Hello world //this is a comment";
preg_replace('/\/\/.*/', '%$0%', $string);

Related

Remove all instances from string

I have a string:
[startstring]hello = guys[endstring] hello guys [startstring]jerk = you[endstring] man this is good!!!
I would like remove everything in between [startstring] and [endstring], all the matches, and also remove the [startstring] and [endstring] from the string. So like the result would be:
hello guys man this is good!!!
and the deleted stuff would be:
[startstring]hello = guys[endstring] hello guys [startstring]jerk = you[endstring] man this is good!!!
See what I mean?
I would like to echo the resulted stuff, without the [startstring] and [endstring] stuff, as shown above. :)
Hope I'm mostly clear. :-)
How would I go about accomplishing this in PHP? Would this envolve some sort of RegEx? Could you provide a sample code?
Thanks so much in advance! :-)
Edit: Could this code be modified or be used somewhat to complete the task?
preg_match_all('/\[startstring\](.*?)\[endstring\]/s', $input, $matches);
To achieve that you just need to change your method name, you should use preg_replace instead preg_match_all:
preg_replace ($pattern, $replacement, $subject)
Searches subject for matches to pattern and replaces them with replacement.
Code
$input = "[startstring]hello = guys[endstring] hello guys [startstring]jerk = you[endstring] man this is good!!!";
$output = preg_replace('/\[startstring\](.*?)\[endstring\]/s', '', $input);
Output
hello guys man this is good!!!

PHP Regex to remove everything after a character

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);

PHP regex title conversion / negative look ahead / toLowerCase

I'm trying to convert some titles in my html pages to <h2>. The pattern is simple.
<?php
$test = "<p><strong>THIS IS A TEST</strong></p><div>And this is Random STUFF</div><p><strong>CP</strong></p>";
$pattern = "/<p><strong>([A-Z ]*?)<\/strong><\/p>/";
$replacement = "<h2>$1</h2>";
$test = preg_replace($pattern, $replacement, $test);
?>
Basically, grab anything that's between <p><strong></strong></p> that is capitalized. Easy enough, so here's the complicated bit.
Firstly, I need to make a single exception. <p><strong>CP</strong></p> must not be converted to <h2>. I tried adding ?!(CP) right after the <p><strong> but it doesn't work.
Secondly, I need to be able to make the first letter capitalized. When I use "ucfirst" with "strtolower" on the preg_replace (ex:ucfirst(strtolower(preg_replace($pattern, $replacement, $test)));), it makes all the characters in the string to lowercase and ucfirst doesn't work as it's detecting "<" to be the first character.
Any hints or am I even going in the right direction?
EDIT
Thanks for the help, it was definitely better to use preg_replace_callback. I found that all my titles were more than 3 characters so I added the limiter. Also added special characters.
Here's my final code:
$pattern = "/<p><strong>([A-ZÀ-ÿ0-9 ']{3,}?)<\/strong><\/p>/";
$replacement = "<h2>$1</h2>";
$test[$i] = preg_replace_callback($pattern, create_function('$matches', 'return "<h2>".ucfirst(mb_strtolower($matches[1]))."</h2>";'), $test[$i]);
Try http://php.net/manual/de/function.preg-replace-callback.php .
You can create a custom function that is called on every match. In this function you can decide to a) not replace CP and b) to not put $1, but ucfirst.
Hope this helps & good luck.

Simple php regex using preg_replace

I want to change strings with the odd """ such as:
He said: "I don't think so"
To be:
He said: "I don't think so"
My current code is:
$sentence = addslashes(preg_replace('/^\&quot\;$/','\"',$var));
What is my problem in the code?
^ and $ will only match the start and end of the whole string (or a whole line in /m mode). Since " doesn't appear like that, your regex whole match it. Just remove the ^ and $ and it should work.
BTW, perhaps you want to use html_entity_decode() instead.
You are probably better off using PHPs htmlspecialchars_decode():
$var = "He said: "I don't think so"";
$sentence = htmlspecialchars_decode($var);
This one may solve your problem:
$yourstring = "He said: "I don't think so"";
$newstring = str_replace(""","\"",$yourstring);
echo $newstring;

Remove excessive line returns

I am looking for something like trim() but for within the bounds of a string. Users sometimes put 2, 3, 4, or more line returns after they type, I need to sanitize this input.
Sample input
i like cats
my cat is happy
i love my cat
hope you have a nice day
Desired output
i like cats
my cat is happy
i love my cat
hope you have a nice day
I am not seeing anything built in, and a string replace would take many iterations of it to do the work. Before I whip up a small recursive string replace, I wanted to see what other suggestions you all had.
I have an odd feeling there is a regex for this one as well.
function str_squeeze($body) {
return preg_replace("/\n\n+/", "\n\n", $body);
}
How much text do you need to do this on? If it is less than about 100k then you could probably just use a simple search and replace regex (searching something like /\n+/ and replace with \n)
On the other hand if you need to go through megabytes of data, then you could parse the text character by character, copying the input to the output, except when mulitple newlines are encountered, in which case you would just copy one newline and ignore the rest.
I would not recommend a recursive string replace though, sounds like that would be very very slow.
Finally managed to get it, needs preg so you are using the PCRE version in php, and also needs a \n\n replacement string, in order to not wipe all line endings but one:
$body = preg_replace("/\n\n+/", "\n\n", $body);
Thanks for getting me on the right track.
To consider all three line break sequences:
preg_replace('/(?:\r\n|[\r\n]){2,}/', "\n\n", $str)
The following regular expression should remove multiple linebreaks while ignoring single line breaks, which are okay by your definition:
ereg_replace("\n\n+", "\n\n", $string);
You can test it with this PHP Regular Expression test tool, which is very handy (but as it seems not in perfect parity with PHP).
[EDIT] Fixed the ' to ", as they didn't seem to work. Have to admit I just tested the regex in the web tool. ;)

Categories