Regular expression does not work with PHP - php

This is a continuation to the previous case: Removing new lines containing spaces
Now I have a working regular expression:
R^[ ]{3}$
which finds new line and 3 spaces after it.
In PHP I use:
$result = preg_replace('/R^[ ]{3}$/', '', $file);
Which should remove such occurrences. However the output remains unchanged. Consider the following example:
UID(*****************ABCDXXX) ALLOW
UID(*****************EFGHXSX) ALLOW
There are 3 spaces in line 2. End result should be:
UID(*****************ABCDXXX) ALLOW
UID(*****************EFGHXSX) ALLOW
Since I get input from a file, here is how I output the result:
foreach ($result as $key => $value) {
if(!empty($value)) {
echo $value . "<br />";
}
}
I also tried this regular expression but, as you might gathered, it did not work:
\n.{3}$

The new line depends on the platform you run your code in, so on the contents of the file. In Windows this is \r\n, in *Nix \n so we should make \r optional.
$result = preg_replace('/\r?\n[\ ]{3}/', '<br />', $file);

Try with this:
$pattern = "/(<(?!\/)[^>]+>)+(<\/[^>]+>)+/";
$html = preg_replace($pattern, '', $html);

Related

PHP preg_replace all text changing

I want to make some changes to the html but I have to follow certain rules.
I have a source code like this;
A beautiful sentence http://www.google.com/test, You can reach here http://www.google.com/test-mi or http://www.google.com/test/aliveli
I need to convert this into the following;
A beautiful sentence http://test.google.com/, You can reach here http://www.google.com/test-mi or http://test.google.com/aliveli
I tried using str_replace;
$html = str_replace('://www.google.com/test','://test.google.com');
When I use it like this, I get an incorrect result like;
A beautiful sentence http://test.google.com/, You can reach here http://test.google.com/-mi or http://test.google.com/aliveli
Wrong replace: http://test.google.com/-mi
How can I do this with preg_replace?
With regex you can use a word boundary and a lookahead to prevent replacing at -
$pattern = '~://www\.google\.com/test\b(?!-)~';
$html = preg_replace($pattern, "://test.google.com", $html);
Here is a regex demo at regex101 and a php demo at eval.in
Be aware, that you need to escape certain characters by a backslash from it's special meaning to match them literally when using regex.
It seems you're replacing the subdirectory test to subdomain. Your case seems to be too complicated. But I've given my best to apply some logic which may be reliable or may not be unless your string stays with the same structure. But you can give a try with this code:
$html = "A beautiful sentence http://www.google.com/test, You can reach here http://www.google.com/test-mi or http://www.google.com/test/aliveli";
function set_subdomain_string($html, $subdomain_word) {
$html = explode(' ', $html);
foreach($html as &$value) {
$parse_html = parse_url($value);
if(count($parse_html) > 1) {
$path = preg_replace('/[^0-9a-zA-Z\/-_]/', '', $parse_html['path']);
preg_match('/[^0-9a-zA-Z\/-_]/', $parse_html['path'], $match);
if(preg_match_all('/(test$|test\/)/', $path)) {
$path = preg_replace('/(test$|test\/)/', '', $path);
$host = preg_replace('/www/', 'test', $parse_html['host']);
$parse_html['host'] = $host;
if(!empty($match)) {
$parse_html['path'] = $path . $match[0];
} else {
$parse_html['path'] = $path;
}
unset($parse_html['scheme']);
$url_string = "http://" . implode('', $parse_html);
$value = $url_string;
}
}
unset($value);
}
$html = implode(' ', $html);
return $html;
}
echo "<p>{$html}</p>";
$modified_html = set_subdomain_string($html, 'test');
echo "<p>{$modified_html}</p>";
Hope it helps.
If the sentence is the only case in your problem you don't need to start struggling with preg_replace.
Just change your str_replace() functioin call to the following(with the ',' at the end of search string section):
$html = str_replace('://www.google.com/test,','://test.google.com/,');
This matches the first occurance of desired search parameter, and for the last one in your target sentence, add this(Note the '/' at the end):
$html = str_replace('://www.google.com/test/','://test.google.com/');
update:
Use these two:
$targetStr = preg_replace("/:\/\/www.google.com\/test[\s\/]/", "://test.google.com/", $targetStr);
It will match against all but the ones with comma at the end. For those, use you sould use the following:
$targetStr = preg_replace("/:\/\/www.google.com\/test,/", "://test.google.com/,", $targetStr);

remove everything between two square brackets

I've been trying to remove some text... between two sets of brackts... for two hours i have tried everything... i've been to existing questions here and the answers don't work for me... so here goes
what i have
[attachment=0:randomID]<!-- ia0 -->randomIMGnam.png<!-- ia0 -->[/attachment:randomID]
i really want to remove all of this from the beginning of a string i was able to remove everything inside the brackets but failed everytime to get rid of the image name
Yes this is from phpbb i've pulled it from my DB no problem but don't want it to be displayed when i echo it.
thanks in advance i really hope I really hope someone can help
edit: what i've tried
1. $extension_pos = strrpos($entry, '<!-- ia0 -->'); // find position of the last dot, so where the extension starts
$output = substr($entry, 0, $extension_pos) . '' . substr($entry, $extension_pos);
2.$output= preg_replace('#\].*?\[#', '', $entry);
$output = preg_replace('/\[[^]]*\]/', '', $entry);
$output explode(']', $entry);
$imagename = preg_replace('#([attachment.*?]).*?([/attachment.*?])#', '$1$2', $entry);
You can use this regex to replace:
$string = ' [attachment=0:randomID]<!-- ia0 -->randomIMGnam.png<!-- ia0 -->[/attachment:randomID]';
$string = preg_replace('/\[(.*?)\]/', '', $string);
You could use regular expression as in example:
<?php
$string = 'test [attachment=0:randomID]randomIMGnam.png[/attachment:randomID] test2 [something]
test3
[/something] test4';
echo preg_replace('#(\[(.*)\](.*)\[/.*\])#Us','',$string);
// output test test2 test4
?>
Using regex might be heavy for this kind of task.
You could instead use a simple reasoning, whenever you meet a open bracket increment a counter by one, whenever you meet a close bracket decrement the counter by one.
And as long as your counter is > 0 just ignore the characters.

I cannot get strpos to work with newline

I am very new to php and cannot find out how to fix this. I have a form and want to pass some string to it and have it checked with another file. It is working fine if all the strings are on the same line but as soon as I put in multiple lines of string, it will fail.
I have a php file with the following code:
<?php
echo "<center><form method='post' enctype='multipart/form-data'>";
echo "<b></b><textarea name='texttofind' cols='80' rows='10'></textarea><br>";
echo "<input name='submit' type='submit' style='width:80px' value='Run' />";
echo "</form></center>";
$texttofind = $_POST['texttofind'];
if(get_magic_quotes_gpc()) {
$texttofind = stripslashes($texttofind);
}
$texttofind = html_entity_decode($texttofind);
$s = file_get_contents ("/home/xxxxx/public_html/abc.txt");
if (strpos ($s, $texttofind) === false) {
echo "not found";
}
else
echo "found";
?>
and in abc.txt, I have
dog
cat
rat
Whenever, I open the php page and type in just dog or cat, it will be fine and show 'found' message but when I type multiple lines like 'dog<enter on keyboard>cat' and click submit button, it will return with the 'not found' message.
What is wrong with the code or anyway to adapt it so that it will be able to search multiple lines?
Thank you in advance.
When you place your search words on new lines you are adding characters that do not exist in your comparison file. Eg when you enter...
dog
cat
rat
You are actually sending a string that looks like...
"dog\ncat\nrat"
Where \n means character 13 or the standard non windows new line character. The fix for this depends on what you want to do. You can search for results using PHP's explode function to convert the input string into an array and then get positions for each word...
$inputs = explode("\n", $_POST['field']);
$positions = array();
foreach($inputs as $val)
$positions[] = str_pos($compareTo, $val);
Now $positions should be an array of the str_pos's that where found for each line.
If you are still trying to search that the comparison file has all of the text you just don't care if it is on a new line or not you can simply strip out the new line characters all together (also remove \r just to be safe)
$inputs = str_replace("\n", "", $_POST['field']);
$inputs = str_replace("\r", "", $inputs);
Now inputs would be "dogcatrat". You can use the second argument of str_replace to set a space instead of a \n to get back to the space separated list.
$inputs = str_replace("\n", " ", $_POST['field']);
$inputs = str_replace("\r", "", $inputs);
Yes we are still ignoring \r all together (silly windows). All the same I suggest reading up on how to use array's, explode & implode and str_replace. Many will comment on this and tell you that str_replace is bad and that you should learn regex. As an experienced developer I find very few cases where regex replacements provide any better functionality in simple character replacement and it will cause you to learn a completely new language of commands. For now ignore those who tell you to use regex but definitely learn regex in the near future. You will need it eventually, just not for something of this nature.
http://php.net/manual/en/language.types.array.php
http://php.net/manual/en/function.explode.php
http://php.net/manual/en/function.implode.php
http://php.net/manual/en/function.str-replace.php
http://php.net/manual/en/function.preg-match.php
<?php
$values=explode("\n",$txttofind);
foreach($values as $value)
{
if (strpos ($s, $value) === false)
{
echo "$value : not found <br>";
}
else
{
echo "$value : found <br>";
}
}
?>

How to remove particular data from file using php

Present data in file ---
Kortrijk]]||75,592||74,790||73,777VWVVLG
Hasselt]]||65,503||68,085||70,584VLIVLG
Sint-Niklaas]]||68,277||68,290||70,016VOVVLG
Ostend]]||69,039||67,279||69,115VWVVLG
|22Tournai]]||67,291||67,379||67,844WHTWAL
|23Genk]]||61,532||62,842||64,095VLIVLG
|24Seraing]]||62,832||60,557||61,237WLGWAL
This is the data set i have in my wiki.txt file, i need to remove all content after "]]||" from all lines.
//Require data after code implementation
Kortrijk
Hasselt
Sint-Niklaas
Ostend
|22Tournai
|23Genk
|24Seraing
This is the code i came across, but dont have any idea how to use it in my code, i followed preg_replace, regular expression etc but all going above my head..help me plz and plz let me know any tutorial link that i can follow for these kind of working(specially regular expression for a novice).
$file="wiki.txt";
file_put_contents($file,str_replace('find','replace',file_get_contents($file)));
try:
$arr = file("wiki.txt"); //will give you contents as array
$newContent = "";
foreach($arr as $key => $val) {
$newContent .=substr_replace($val, '', strpos($val, ']'))."\n";
}
//add changed content back to file
file_put_contents("wiki.txt", $newContent);
//result is:
Kortrijk
Hasselt
Sint-Niklaas
Ostend
|22Tournai
|23Genk
|24Seraing
preg_replace('/]]\|\|.*$/m', '', $fnames);
Matches ']]||' literally, then all characters (.*) until the end of a line '$' and replaces them with ''.
Also: Check out this tutorial on RegExp
Rather than "change" the file, you probably want to open the file, read the contents, then write the parts you want to a new file. If everything goes as planned, replace the old file with the new file. Much safer that way.
<?php
$lines = file("input.txt");
$output = "";
foreach ($lines as $line) {
$output .= substr($line, 0, strpos($line, "]")) . "\n";
}
file_put_contents("output.txt", $output);
Lots of ways to solve this.

preg_replace suddenly stops making distinctions

Confounded. I've been using the below IF PREG_MATCH to distinguish between words which entire words and words which are parts of other words. It has suddenly ceased to function in this script, and any other script I use, which depend on this command.
The result is it finds parts of words, although you can see it is explicitly told to find only entire words.
$word = preg_replace("/[^a-zA-Z 0-9]+/", " ", $word);
if (preg_match('#\b'.$word.'\b#',$goodfile) && (trim($word) != "")) {
$fate = strpos($goodfile,$word);
print $word ." ";
print $fate ."</br>";
If you only want to read the first word of a line of a text file, like your title suggests, try another method:
// Get the file as an array, each element being a line
$lines = file("/path/to/file");
// Break up the first line by spaces
$words = explode(" ", $lines[0]);
// Get the first word
$firstWord = $words[0];
This would be faster and cleaner than explode and you won't be making any array
$first_word = stristr($lines, ' ', true);

Categories