Simple regular expression using preg_match - preg-match

I am trying to retrieve the three digit number after this word and semi colon.
REF: 222
The code i have below works but its not good because its getting 3digit numbers from the $decoded_message string.
What i really want is only to grab three digit number after the word REF: ###
if (preg_match("([0-9]{3})", $decoded_message, $matches)) {
echo "Match was found <br />";
echo "ref = ".$matches[0];
}
Thanks in advance

You can search for REF: [0-9]{3} and then remove the REF: part.
if (preg_match("/REF: [0-9]{3}/", $decoded_message, $matches)) {
echo "Match was found <br />";
echo "ref = ".substr( $matches[0], 5 );
}

You may simply replace "REF: " by using
$output = preg_replace("/REF: /","", "REF: 222");
Afterwards, only the number should be contained in $output.

Related

Using explode but after first <br><br> Pattern

I am using explode to create an array from string and using pattern <br><br> but in my case i want it to be start after first match <br><br>. Means when first time it gets <br><br> then it skip and create an array from second time and so on match <br><br>
<?php
$myString = "Welcome, j.<br><br>
 
(1) this revisional application has been preferred under read with section of the against the order passed by the learned special judge, ndps act, 6th court at barasat.<br><br>
(2) case of the petitioner is that he along with other accused persons are facing trial case, as pending the learned additional sessions judge, 6th court. barasat.";
$myArray = explode('<br><br>', $myString);
// $arr = ltrim($myArray, ' ');
echo "<pre>"; print_r($myArray);
foreach($myArray as $key => $value)
{
$whatIWant = substr($value, strpos($value," "));
echo ucfirst($whatIWant);
}
Basically my task is to Capitalize first letter of Second word i.e this and case.
You can use array_shift() function to shift your array by one element and skip first item in your array.
php document for array_shift
$myArray = explode('<br><br>', $myString);
array_shift($myArray);
foreach($myArray as $key => $value)
{
$whatIWant = substr($value, strpos($value," "));
echo ucfirst($whatIWant);
}
I would try using preg_match_all instead.
The code below looks for the pattern (\d+) (\w+)
\d+ = 1 or more digits
\w+ = 1 or more alphanumeric letters
If you were to add (3)... (4)... and so on, it would match all of them
<?php
$myString = "Welcome, j.<br><br>
(1) this revisional application has been preferred under read with section of the against the order passed by the learned special judge, ndps act, 6th court at barasat.<br><br>
(2) case of the petitioner is that he along with other accused persons are facing trial case, as pending the learned additional sessions judge, 6th court. barasat.";
preg_match_all("/(\(\d+\))\s(\w+)/", $myString, $all_matches);
foreach ($all_matches[1] as $idx => $match) {
$original = "{$match} " . $all_matches[2][$idx];
$replacement = "{$match} " . ucfirst($all_matches[2][$idx]);
$myString = str_replace($original, $replacement, $myString);
}
echo $myString;

XQuery nested for clause

I kept getting this error in XQuery, but I was sure that I opened and closed the brackets. What may go wrong with this query?
XPST0003 XQuery syntax error near #...{ $x/name }</name> {for#:
expected "}", found "{"
This is the query
<myquery>
<A>
{for $x in doc("example.xml")/example/A
where $x/name = "United States"
return
<name>{ $x/name }</name> (: error reported at this line of code :)
{for $y in $x/B
let $z := $y/C div $y/D
order by $z
return
<B>
<C>{$y/name/text()}</C>
<ratio>{ $z }</ratio>
</B>
}
}
</A>
</myquery>
Given you want to return the name tags followed by B tags, you will have to return a sequence:
<myquery>
<A>{
for $x in doc("example.xml")/example/A
where $x/name = "United States"
return ( (: Return a sequence here :)
<name>{ $x/name }</name>, (: Be aware of the comma :)
for $y in $x/B
let $z := $y/C div $y/D
order by $z
return
<B>
<C>{$y/name/text()}</C>
<ratio>{ $z }</ratio>
</B>
) (: end of sequence :)
}</A>
</myquery>
I also removed the unnecessary curly brackets around the FLWOR expression, and be aware I added a comma after the name tag.

preg replace remove the same repeated non-word character

I want to remove the same repeated non-word character.
My code looks like this:
<?php
$name = 'Malines - Blockbuster (prod. Malines) ***** (((((( &%^$';
echo preg_replace('/[^\pL\pN\s]{2,}/u', '', $name);
?>
Malines - Blockbuster (prod. Malines) ***** (((((( &%^$ should be Malines - Blockbuster (prod. Malines) &%^$
Only repeated non-word character should be removed. Could you help me?
You must use back-reference to say that the second character is the same as the one before :
/([^\pL\pN\s])\1+/u
Using the same idea than Arlaud Agbe Pierre (that is the way to do it), the pattern can be shorten using the Xan character class. \p{Xan} is the union of \p{L} and \p{N}. \P{Xan} (with an uppercase "p") is the negation of this class (i.e. all that is not a letter or a number).
$str = 'Malines - Blockbuster (prod. Malines) ààà ***** (((((( &%^$';
echo preg_replace('~(\P{Xan})\1+~u', '$1', $str);
Note: in this pattern, consecutive white characters are removed too.
an other way:
echo preg_replace('~(\P{Xan})\K\1+~u', '', $str);
where \K resets the begining of the match from the match result. (note that you can however define capturing groups before that you can use after)

Allow a-z, A-Z, 0-9, space and -. preg_match

How can I allow a-z, A-Z, 0-9, - and space with preg_match.
I currently have the following:
if (!preg_match("/^[_a-zA-Z0-9]+$/", $name))
Also a side-question, does any of you know a good guide to learn preg_match.
I think this will work for you
<?php
$result = preg_match("/^[a-zA-Z0-9 \s]+$/", $name));
?>
just give space and "-" in your brackets [ ]
example
<?php
$name = "A- ";
if(preg_match("/^[_a-zA-Z0-9- ]+$/", $name))
{
echo "hello";
}
?>
and a good site for studying : link
only [a-z, A-Z, 0-9 and Space] allow. We delete the first space with LTRIM.
<?php
$name = "Hasan Yİlmaz SÄ°MFER ";
if(ltrim(preg_match('/^[a-zA-ZığüşöçİGÜŞÖÇ0-9- ]+$/', $name2), ' '))
{
echo $name;
}
?>
Using /^[a-zA-Z'- ]+$/ Shows the below given warning
"preg_match(): Compilation failed: range out of order in character
class at offset 10"
Instead of the above-mentioned code, you can use /^[a-zA-Z' -]+$/. This will not show the warning.!

Automatic multiline labels in Graphviz?

I'm using Graphviz to draw some graphs. I'm using labels on nodes and I can put in "\n" to force it to split the label across 2 lines. Is there some way to get Graphviz (or dot which I'm using) to automatically see that it should split some nodes labels, and for it itself to make the best choice automagically?
Yes, HTML-like labels (<...>) support tag, using which you can break the lines. E.g.
"A" -> "B"
[label = <1. <br/>
2. <br/>
3. <br/>
4. <br/>
.... <br/>
> color="blue" style="dashed"];
These also work when embedding Graphviz in LaTeX, where \n would not.
I've also searched for this, but I don't think it's possible in the current version. The current "solution" is to write code that automatically adds the "\n" every few characters, based on the minimum distance between nodes (nodesep attribute, if I'm not mistaken).
One person wrote a Perl script to achieve this. I found it in his blog: Text wrapping with dot (graphviz).
⚠ Note
This only works if the labels are in the format node [ label=”node label” ]. If the nodes are declared directly (e.g. ”node label”) then it doesn’t work
Perl script:
#!/usr/bin/perl
use strict;
my $usage = "setdotlabelwidth [char-width] < [dotfile]";
my $width = shift() or die("Usage: $usage $!");
while(<STDIN>)
{
if(m/label="(.*?)"/)
{
my $labeltext = $1;
my #words = split(/ /, $labeltext);
my #newtext = ();
my $newline = "";
foreach my $word(#words)
{
if( length($newline) > 0 and
length($newline) + length($word) > $width )
{
push(#newtext, $newline);
$newline = "";
}
$newline .= " " if( length($newline) > 0 );
$newline .= $word;
}
push(#newtext, $newline) if( length($newline) > 0 );
my $newlabel = join("\\n", #newtext);
s/label=".*?"/label="$newlabel"/;
}
print;
}
Save this program as setdotlabelwidth, then simply pipe the output into GraphViz. If for example you want to set the width to 35 characters, then the command is:
./setdotlabelwidth 35 < tile-error-correction.dot | dot -Tpng -o tile-error-correction.png
Before:
After:
(Not sure how we're supposed to deal with duplicate questions?)
dot2tex (latex + graphviz) handles text wrapping,
along with other workarounds to the typesetting limitations of graphviz.
You'll find a short example at this duplicate question,
with prescribed fixed line width.

Resources