I have a one string which is include ,(comma) and .(dot) .
I want to split both comma and dot . I am confused to split by dot and comma .
I would go with a regex first and then loop the results, something like this:
$html = <<< LOB
this is example of string , test . R.K
this is second example of string , test2 . R.K2
LOB;
preg_match_all('/^.*?,(.*?)\.(.*?)$/im', $html, $matches, PREG_PATTERN_ORDER);
for ($i = 0; $i < count($matches[0]); $i++) {
echo $matches[1][$i] . " " . $matches[2][$i];
}
//test R.K
//test2 R.K2
DEMO
Related
i need to convert a perl array to a single string variable, containing all array items separated with newlines.
my $content = "";
#names=('A','C','C','D','E');
$content = $content . join($", #names) . "\n";
print $content;
I intend the output to be like:
A
C
C
D
E
But i get:
A C C D E
Why isn't the newline \n character being honoured?
Since it appears that you want a newline not just between each line, but after the last one too, you can use any of the following:
join("\n", #names) . "\n"
join("", map "$_\n", #names)
join("\n", #names, "")
These are equivalent except when the array in empty. In that situation, the first results in a newline, and the other result in an empty string.
By the way,
$content = $content . EXPR;
can be written as
$content .= EXPR;
To join an array with newlines in between, use
join("\n", #array)
Your code uses the contents of the $" variable as the separator, which by default contains a space.
Do this instead:
$content = $content . join("\n", #names);
The $" variable holds the value that Perl uses between array elements when it interpolates an array in a double-quoted string. By default (and you haven't changed it), it's a space.
Perhaps you were thinking about the input or output record separators, $/ or $\.
But, you don't really want to play with those variables. If you want a newline, use a newline:
join "\n", #array;
I have an array I can print out as "abcd" however I am trying to print it as "a>ab>abc>abcd". I can't figure out the nested loop I need within the foreach loop I have. What loop do I need within it to print it this way?
my $str = "a>b>c>d";
my #words = split />/, $str;
foreach my $i (0 .. $#words) {
print $words[$i], "\n";
}
Thank you.
You had the right idea, but instead of printing the word at position i, you want to print all the words between positions 0 and i (inclusive). Also, your input can contain multiple strings, so loop over them.
use warnings;
while (my $str = <>) { # read lines from stdin or named files
chomp($str); # remove any trailing line separator
my #words = split />/, $str; # break string into array of words
foreach my $i (0 .. $#words) {
print join '', #words[0 .. $i]; # build the term from the first n words
print '>' if $i < $#words; # print separator between terms (but not at end)
}
print "\n";
}
There are many other ways to write it, but hopefully this way helps you understand what's happening and why. Good luck!
one liner:
perl -e '#a=qw(a b c d); for(#a) {$s.=($h.=$_).">"} $s=substr($s,0,-1);print $s'
I would do it like this:
#!/usr/bin/perl
use strict;
use warnings;
my $str = "a>b>c>d>e>f>g";
my #words = split />/, $str;
$" = '';
my #new_words;
push #new_words, "#words[0 .. $_]" for 0 .. $#words;
print join '>', #new_words;
A few things to explain.
Perl will expand array variables in a double-quoted string. So something like this:
#array = ('x', 'y', 'z');
print "#array";
will print x y z. Notice there are spaces between the elements. The string that is inserted between the elements is controlled by the $" variable. So by setting that variable to an empty string we can remove the spaces, so:
$" = '';
#array = ('x', 'y', 'z');
print "#array";
will print xyz.
The most complex line is:
push #new_words, "#words[0 .. $_]" for 0 .. $#words;
That's just a compact way to write:
for (0 .. $#words) {
my $new_word = "#words[0 .. $_]";
push #new_words, $new_word;
}
We iterate across the integers from zero to the last index in #words. Each time around the loop, we use an array slice to get a list of elements from the array, convert that to a string (by putting it in double-quotes) and then push that string onto #new_words.
This is what I ended up with, It's the only way I could understand and get the output I was looking for.
use strict;
use warnings;
my $str = "a>b>c>d>e>f>g";
my #words = split />/, $str;
my $j = $#words;
my $i = 0;
my #newtax;
while($i <= $#words){
foreach my $i (0 .. $#words - $j){
push (#new, $words[$i]);
}
if($i < $#words){
push(#new, ">");
}
$j--;
$i++;
}
print #new;
This output "a>ab>abc>abcd>abcde>abcdef>abcdefg"
I'm doing an Array that contents each word of a phrase. When I try to split it and print the length then the console gives me an enormous number such as 111039391231319239188238139123919232913123... (more lines)
why?
Here's my code:
$mynames = $texto3;
print $mynames. "\n";
#nameList = split(' ', $texto3);
#print #nameList.length();
for ($to = 0; $to<#nameList.length; $to++){
if($to<#nameList.length) {
#nameList[$to] = #nameList[$to] . "_" . #nameList[$to++];
}
print $to;
#print #nameList[$to] . "\n";
}
$string_level2 = join(' ', #nameList);
#print $string_level2;
To get the length of an array use scalar #nameList instead of #nameList.length.
A typical for-loop uses the less-than operator when counting up, e.g.:
for ( $to = 0; $to < scalar(#nameList); $to++ ) ...
You should never use a post-increment unless you understand the side effects. I believe the following line:
#nameList[$to] = #nameList[$to] . "_" . #nameList[$to++];
... should be written as ...
$nameList[$to] = $nameList[$to] . "_" . $nameList[$to + 1];
Finally the comparison you use should account for the boundary condition (because you refer to $to + 1 inside the loop):
if( $to < (scalar(#nameList) - 1) ) {
$nameList[ $to ] = $nameList[ $to ] . "_" . $nameList[ $to + 1 ];
}
I am confused about the outcome of this code.
my #lines;
for (my $count = 0; $count < 3; $count++) {
print "Give me input again ";
chomp (my $line = <STDIN>);
$lines[$count] = $line;
}
$" = "|";
print "#lines\n";
When I run the code, how does this: $" = "|"; work?
The results are One|Two|Three. How does the code work so that it puts "|" between each input?
It's simply what interpolation of arrays into double-quoted strings does.
"$foo\n"
is identical to
$foo . "\n"
and
"#lines\n"
is identical to
join($", #lines) . "\n"
This is documented in perldata and in perlvar.
$" is just a special variable name in perl that tells the interpreter how to separate array elements in double-quoted string context. The default value is a space, but the above code tells perl to use | instead. Hence One|Two|Three instead of the default of One Two Three if you left out that line.
See http://perldoc.perl.org/perlvar.html#General-Variables for more detail.
I need make something that includes a function that uses explode to create an array. I have seen several examples, but near the end I really get confused! Is there a simple readable way for this? (//comments?)
Take for instance a piece of text:
"This is a simple text I just created".
The output should look like this:
This is a
simple text I
just created
So the explode should split the text into lines of 3 words each.
$text = "This is a simple text I just created";
$text_array = explode(" ", $text);
$chunks = array_chunk($text_array, 3);
foreach ($chunks as $chunk) {
$line = $impode(" ", $chunk);
echo $line;
echo "<br>";
}
Try this is what you need:
<?php
$text = "This is a simple text I just created";
$text_array = explode(' ', $text);
$i = 1; // I made change here :)
foreach($text_array as $key => $text){
if(ceil(($key + 1) / 3) != $i) { echo "<br/>"; $i = ceil(($key + 1) / 3); }
echo $text.' ';
}
?>
Result:
This is a
simple text I
just created
Use substr() function link
Example:
<?php
$rest = substr("abcdef", -1); // returns "f"
$rest = substr("abcdef", -2); // returns "ef"
$rest = substr("abcdef", -3, 1); // returns "d"
?>
In your case:
<?php
$rest = substr("This is a simple text I just created", 0, 15); //This will return first 15 characters from your string/text
echo $rest; // This is a simpl
?>
explode just splits the string at a specified character. There's nothing more to it.
explode(',', 'Text,goes,here');
This splits the string whenever it meets a , and returns an array.
to split by a space character
explode(' ', 'Text goes here');
This splits only by a space character, not all whitespace. Preg_split would be easier to split by any whitespace
So something like...
function doLines($string, $nl){
// Break into 'words'
$bits = explode(' ', $string);
$output = '';
$counter=0;
// Go word by word...
foreach($bits as $bit){
//Add the word to the output...
$output .= $bit.' ';
//If it's 3 words...
if($counter==2){
// Remove the trailing space
$output = substr($output, 0, strlen($output)-1);
//Add the separator character...
$output .=$nl;
//Reset Counter
$counter=0;
}
}
//Remove final trailing space
$output = substr($output, 0, strlen($output)-1);
return $output;
}
Then all you have to is:
echo doLines("This is a simple text I just created", "\n");
or
echo doLines("This is a simple text I just created", "<br />");
..depending if you just want new lines or if you want HTML output.