What Is the Ruby Equivalent of Preg_Quote()

What is the Ruby equivalent of preg_quote()?

You want Regexp.escape.

str = "[...]"
re = /#{Regexp.escape(str)}/
"la[...]la[...]la".gsub(re,"") #=> "lalala"

Ruby: can I avoid lots of escaping in a regex?

Use the %r syntax:

if ( %r{//\s*\$Source\$} =~ line)
^^ I'm not sure whether ruby would allow unescaped `$` here or not

Regex doesn't work with PHP, but works in Ruby

Use a different regex delimiter and don't forget to enable multi-line modifier (?m) inorder to make your regex to work on multiple lines.

$filename = 'files/Dial.txt';
$input_lines=fonl($filename,80);
echo $input_lines;
$pattern = "(?m)^\[(?<DateTime>[^]]+)\]\s+(?<TypeConnection>\b.*?(?:\W+\w+)}?\W+.*?\b)\s+'(?<User>.*?)'\s+(?<Detail>.*?$)";
//$pattern = preg_quote($pattern, '/');
preg_match_all("~".$pattern."~", $input_lines, $output_array);
print_r($output_array);

Is there a RegExp.escape function in JavaScript?

The function linked in another answer is insufficient. It fails to escape ^ or $ (start and end of string), or -, which in a character group is used for ranges.

Use this function:

function escapeRegex(string) {
return string.replace(/[/\-\\^$*+?.()|[\]{}]/g, '\\$&');
}

While it may seem unnecessary at first glance, escaping - (as well as ^) makes the function suitable for escaping characters to be inserted into a character class as well as the body of the regex.

Escaping / makes the function suitable for escaping characters to be used in a JavaScript regex literal for later evaluation.

As there is no downside to escaping either of them, it makes sense to escape to cover wider use cases.

And yes, it is a disappointing failing that this is not part of standard JavaScript.

What special characters must be escaped in regular expressions?

Which characters you must and which you mustn't escape indeed depends on the regex flavor you're working with.

For PCRE, and most other so-called Perl-compatible flavors, escape these outside character classes:

.^$*+?()[{\|

and these inside character classes:

^-]\

For POSIX extended regexes (ERE), escape these outside character classes (same as PCRE):

.^$*+?()[{\|

Escaping any other characters is an error with POSIX ERE.

Inside character classes, the backslash is a literal character in POSIX regular expressions. You cannot use it to escape anything. You have to use "clever placement" if you want to include character class metacharacters as literals. Put the ^ anywhere except at the start, the ] at the start, and the - at the start or the end of the character class to match these literally, e.g.:

[]^-]

In POSIX basic regular expressions (BRE), these are metacharacters that you need to escape to suppress their meaning:

.^$*[\

Escaping parentheses and curly brackets in BREs gives them the special meaning their unescaped versions have in EREs. Some implementations (e.g. GNU) also give special meaning to other characters when escaped, such as \? and +. Escaping a character other than .^$*(){} is normally an error with BREs.

Inside character classes, BREs follow the same rule as EREs.

If all this makes your head spin, grab a copy of RegexBuddy. On the Create tab, click Insert Token, and then Literal. RegexBuddy will add escapes as needed.

How to run Ruby/Python scripts from inside PHP passing and receiving parameters?

Have PHP open the Ruby or Python script via proc_open, piping the HTML into STDIN in the script. The Ruby/Python script reads and processes the data and returns it via STDOUT back to the PHP script, then exits. This is a common way of doing things via popen-like functionality in Perl, Ruby or Python and is nice because it gives you access to STDERR in case something blows chunks and doesn't require temp files, but it's a bit more complex.

Alternate ways of doing it could be writing the data from PHP to a temporary file, then using system, exec, or something similar to call the Ruby/Python script to open and process it, and print the output using their STDOUT.

EDIT:

See @Jonke's answer for "Best practices with STDIN in Ruby?" for examples of how simple it is to read STDIN and write to STDOUT with Ruby. "How do you read from stdin in python" has some good samples for that language.

This is a simple example showing how to call a Ruby script, passing a string to it via PHP's STDIN pipe, and reading the Ruby script's STDOUT:

Save this as "test.php":

<?php
$descriptorspec = array(
0 => array("pipe", "r"), // stdin is a pipe that the child will read from
1 => array("pipe", "w"), // stdout is a pipe that the child will write to
2 => array("file", "./error-output.txt", "a") // stderr is a file to write to
);
$process = proc_open('ruby ./test.rb', $descriptorspec, $pipes);

if (is_resource($process)) {
// $pipes now looks like this:
// 0 => writeable handle connected to child stdin
// 1 => readable handle connected to child stdout
// Any error output will be appended to /tmp/error-output.txt

fwrite($pipes[0], 'hello world');
fclose($pipes[0]);

echo stream_get_contents($pipes[1]);
fclose($pipes[1]);

// It is important that you close any pipes before calling
// proc_close in order to avoid a deadlock
$return_value = proc_close($process);

echo "command returned $return_value\n";
}
?>

Save this as "test.rb":

#!/usr/bin/env ruby

puts "<b>#{ ARGF.read }</b>"

Running the PHP script gives:

Greg:Desktop greg$ php test.php 
<b>hello world</b>
command returned 0

The PHP script is opening the Ruby interpreter which opens the Ruby script. PHP then sends "hello world" to it. Ruby wraps the received text in bold tags, and outputs it, which is captured by PHP, and then output. There are no temp files, nothing passed on the command-line, you could pass a LOT of data if need-be, and it would be pretty fast. Python or Perl could easily be used instead of Ruby.

EDIT:

If you have:

HTML2Markdown.new('<h1>HTMLcode</h1>').to_s

as sample code, then you could begin developing a Ruby solution with:

#!/usr/bin/env ruby

require_relative 'html2markdown'

puts HTML2Markdown.new("<h1>#{ ARGF.read }</h1>").to_s

assuming you've already downloaded the HTML2Markdown code and have it in the current directory and are running Ruby 1.9.2.

strange preg_quote behavior

because \ escapes the next one, as every \ needs to be escaped.

with a single \ it escapes the next character witch is u, but \u isn't a char code so it is displayed like a simple character

An explode() function that ignores characters inside quotes?

str_getcsv($str, '/')

There's a recipe for <5.3 on the linked page.

Filter array to keep elements where the key exists in the value string

From PHP5.6, array_filter() gained the ARRAY_FILTER_USE_BOTH flag. This makes array_filter() an equivalent functional-style technique.

Code: (Demo)

var_export(
array_filter(
$array,
function($haystack, $needle) {
return strpos($haystack, $needle) !== false;
},
ARRAY_FILTER_USE_BOTH
)
);

One advantage of this is that $result doesn't need to be declared. On the other hand, despite the fact that it can technically be written as a one-liner, it would make a very long line of code -- something that puts the code near or over the soft character limit per line according to PSR-12 coding standards. So there is very little to compel you to change your code so far.

The good news is that PHP8 introduced str_contains() specifically to offer a clean, native, case-sensitive function to replace strpos() and its obligatory strict boolean false check.

Code: (Demo)

var_export(
array_filter($array, 'str_contains', ARRAY_FILTER_USE_BOTH)
);

This returns the same desired output, is a functional-style, one-liner, and concisely spans just 59 characters. I would recommend this approach.

To understand what is happening, the verbose syntax with array_filter() where str_contains() is not called by its string name looks like this:

var_export(
array_filter(
$array,
fn($haystack, $needle) => str_contains($haystack, $needle),
ARRAY_FILTER_USE_BOTH
)
);

How to use an environment variable in sed when finding strings between two patterns?

To change the delimiter, you need to escape the first one, i.e. something like, \!FIND!. Also, it is best to use single quotes, leave them when needed and use double quotes for variable interpolation. Then your command looks like this:

sed -n '\!'"$var1"'!,\!'"$var2"'!p' inpu


Related Topics



Leave a reply



Submit