Echo string that contains words concatenated without using array-PHP - php

I have a string which comprises of the words the user input in it so I don't know how many words will be there and what will be the index of each word so that I can find substring out of this. Can anyone tell me how to echo it without using or converting it into array and add next line whenever there is space in string. I am newbie to php. I checked for split method, explode method, all inbuilt methods are converting it into array which i dont need.
$var= "This is a sample code."
I want output like this:
This
is
a
sample
code
I tried this but it didnt work for me.
$count= str_word_count($var);
echo "$count";
$strlen= strlen($var);
for($i=0; $i<(int)$strlen;$i++ ){
if($var contains " "){
echo "\n";
}else {
echo $var;
}
}
I would appreciate your help. Thank you.

Use str_replace()
echo str_replace(" ", "\n", $var);
but you also can perform regular expression, that can give you maybe a better answer, it will be able to check only words, ignoring multiple spaces or other space characters.
$var= "This is a sample code.";
if ( preg_match_all("/(\w+)/si", $var, $m ) ){
echo implode("\n", $m[1]);
}

Without other builtin functions and just using for loop , This will give the expected output
for($i=0; $i<(int)$strlen;$i++ ){
if($var[$i]==" "){
echo "<br>";
}else if($var[$i] !='.'){
echo $var[$i];
}
}

Related

Counting Variables using PHP

Building a simple jQuery/PHP setup where for example the PHP will store 5 variables each containing a simple string. These variables are all separate and not in an array. The jQuery used is just a simple fadeIn/fadeOut function which fades out the 1st string and fades in the 2nd string. Got all that working.
However this is for a client who doesn't really even know what a variable is and has asked that the 5 strings be "changable" so I'm creating a seperate PHP file that contains the strings so that the client can just open that file and change the strings within there and possibly add/delete strings from the file.
What I want the php to do is "count" how many variables there are then echo each string depending on how many variables there are. Variables are named like so
$text_0 = "Its a sentence";
$text_1 = "Its another sentence";
$text_2 = "Its a final sentence";
so obviously need a for statement
for(i=0;i<WHATGOESHERE?;i++){
echo $text_[i];
}
Thanks for any help.
If you want it to be editable for a non techguy, then dont even use the variables as its to easy to forget a ; or a $ or whatever. Just create a plain text file and in PHP use it as an array.
An added bonus is that the none tech guy is not able to inject PHP code to your system.
file.txt:
Its a sentence
Its another sentence
Its a final sentence
show.php:
<?php
$lines = file('file.txt');
//below is just an example, obviously it should be your jquery code
foreach ($lines as $line_num => $line) {
echo "Line #<b>{$line_num}</b> : " . htmlspecialchars($line) . "<br />\n";
}
//length would be count($lines) and upper bound count($lines)-1
?>
Give this to your non-techie:
Its a sentence
Its another sentence
Its a final sentence
Convert it into an array with:
$sentences = file('sentences.txt', FILE_SKIP_EMPTY_LINES | FILE_IGNORE_NEW_LINES);
Done.
<?php
$text_0 = 'a';
$text_1 = 'b';
$text_2 = 'c';
$vars = preg_grep('#^text_\d+$#', array_keys(get_defined_vars()));
var_dump($vars);
?>
It's better to create array $text..

How to extract substring from duplicate strings?

i have a specific problem .I am retrieving data in string format in PHP. I have to seperate the specific values from the string.My string looks like this
Barcode formatQR_CODEParsed Result TypeURIParsed Resulthttp://www.myurl.co.uk var ga.
Barcode formatQR_CODEParsed Result TypeTEXTParsed ResultMy Coat var ga.
As you can see from above two examples, The text after "Barcode formatQR_CODEParsed Result Type" and "Parsed Result" are changing.
I have tried strstr function but it is not giving me desired output as the words "Parsed Result" is repeating twice.How can i extract ANY value /text that will come after these?How can I separate them?I would appreciate if someone could guide as i am new bee.
Thanks
The fastest way is to parse this piece of HTML code with SimpleXML and get <b> children's values.
just walk through the strings until you find the first difference. Shouldn't be a problem?
$str1 = "Hello World";
$str2 = "Hello Earth";
for($i=0; $<min(strlen($str1),strlen($str2)); $i++){
if ($str1[$i] != $str2[$i]){
echo "Difference starting at pos $i";
}
}
or something like that. Then you can use substr to remove the equal part.
edit: IF your Strings always have the same Pattern, with values enclosed in <b> you can perfectly use a Regular-Expression to get the values.
I have found the solution .We can extract strings this way:
<?
$mycode='Barcode formatQR_CODEParsed Result TypeURIParsed Resulthttp://www.myurl.co.uk var ga';
$needle = 'Parsed Result';
$chunk=explode($needle,$mycode);
$mychunky= $chunk[2];
$needle = 'var ga';
$result = substr($mychunky, 0, strpos($mychunky, $needle));
print($result);
?>
This should work for you. Also you can extend this idea futher and develop by your own needs.
$string = "Barcode formatQR_CODEParsed Result TypeURIParsed Resulthttp://www.myurl.co.uk var ga." ;
$matches = array() ;
$pattern = "/Type([A-Z]+)Parsed Result([^>]+) var ga./" ;
preg_match($pattern, $string, $matches) ; // Returns boolean, but we need matches.
Then get the occurences:
$matches[0] ; // The whole occurence
$matches[1] ; // Type - "([A-Z]+)"
$matches[2] ; // Result - "([^>]+)"
So you use elements with indeces 1 and 2 as Type and Result respectively. Hope it can help.

php trim function trims extra Less-than/Greater-than signs

I have a question about the PHP trim function.
Consider the following:
$x= '<p>blah</p>';
$x= trim(trim($x, '<p>'), '</p>');
echo htmlentities($x) . "<br />";
This works as expected and prints blah
.
$x= '<p><b>blah</b></p>';
$x= trim(trim($x, '<p>'), '</p>');
echo htmlentities($x) . "<br />";
This prints b>blah</b
I'm not looking for other ways around this.
I do wonder why the trim function shows this behavior (stripping the extra Less-than/Greater-than sign).
Thanks in advance.
trim treats the 2nd argument as a list of characters that can be removed, not as a continuous string. This explains why b remains, but < and > are removed.
This is a default behaviour of trim function. You expect it to trim the exact string, but second parameter is instead a list of characters and any of them will be trimmed if found at each side of the string.
You could use simple RegEx like this:
$x = preg_replace(array('#^<p>#i', '#</p>$#i'), '', $x);

Using a string as an expression to be send to eval() and replacing a sub-string with a vriable value PHP

I need some help with basic syntax in PHP,
I got the following string :
$str = "return (strlen(replace) <= 5 && strlen(replace) >= 1);";
and I got a variable : $var = "VariableValue";
and the st_replace function as : str_replace('replace', $var, $str);
What I am trying to do is actually use eval in somehing like:
if(eval($str)){//This should now make the if condition **look like**
//if(strlen(*'VariableValue'*)...)
//
echo 'Success';
}else{
echo 'Ask the guys at StackOverFlow :),sure after searching for it';
}
So if you notice what is if(strlen('VariableValue')...) this is what I want to do,make the final if statement after eval containing the vars value WITH QUOTES so strlen actually process it,
I hope I made clear as needed :)
Thanks in advance
Try it like this
$str = "return (strlen(##replace##) <= 5 && strlen(##replace##) >= 1);";
$var = 'test';
// you have to assign the str_replace to $str again. And use " around the $var.
$str = str_replace('##replace##', '"' . addslashes($var) . '"', $str);
if (eval($str)) {
echo 'Success';
}
else {
echo 'Ask the guys at StackOverFlow :),sure after searching for it';
}
I added the ## around replace because it's a good idea to always have a somewhat unique string to replace... like when you expand your eval'd code to include str_replace, then that would be replaced too otherwise.
EDIT
Escaped the $var with addslashes as per #Erbureth's comment.
aYou don't need eval() for that (there are reason why it is sometimes called evil()...).
Just try a condition like that:
if ( (strlen($var) <= 5) && (strlen($var) >= 1) )

How to search for a pattern like [num:0] and replace it?

I know there are lots of tutorials and question on replacing something in a string.
But I can't find a single one on what I want to do!
Lets say I have a string like this
$string="Hi! [num:0]";
And an example array like this
$array=array();
$array[0]=array('name'=>"na");
$array[1]=array('name'=>"nam");
Now what I want is that PHP should first search for the pattern like [num:x] where x is a valid key from the array.
And then replace it with the matching key of the array. For example, the string given above should become: Hi! na
I was thinking of doing this way:
Search for the pattern.
If found, call a function which checks if the number is valid or not.
If valid, returns the name from the array of that key like 0 or 1 etc.
PHP replaces the value returned from the function in the string in place of the pattern.
But I can't find a way to execute the idea. How do I match that pattern and call the function for every match?
This is just the way that I am thinking to do. Any other method will also work.
If you have any doubts about my question, please ask in comments.
Try this
$string="Hi! [num:0]";
$array=array();
$array[0]=array('name'=>"na");
$array[1]=array('name'=>"nam");
echo preg_replace('#(\!)?\s+\[num:(\d+)\]#ie','isset($array[\2]) ? "\1 ".$array[\2]["name"] : " "',$string);
If you don't want the overhead of Regex, and your string format remains same; you could use:
<?php
$string="Hi! [num:0]";
echo_name($string); // Hi John
echo "<br />";
$string="Hello! [num:10]";
echo_name($string); // No names, only Hello
// Will echo Hi + Name
function echo_name($string){
$array=array();
$array[0]=array('name'=>"John");
$array[1]=array('name'=>"Doe");
$string = explode(" ", $string);
$string[1] = str_replace("[num:", "", $string[1]);
$string[1] = str_replace("]", "", $string[1]);
if(array_key_exists($string[1], $array)){
echo $string[0]." ".$array[$string[1]]["name"];
} else {
echo $string[0]." ";
}
}// function echo_sal ENDs
?>
Live: http://codepad.viper-7.com/qy2uwW
Assumptions:
$string always will have only one space, exactly before [num:X].
[num:X] is always in the same format.
Of course you could skip the str_replace lines if you could make your input to simple
Hi! 0 or Hello! 10

Categories