I've a string of text like this:
Intro Title ### Some description ### a link \\\
Intro Title Two ### Description Two ### link 2 \\\
And so ... can be infinite
I use explode to be able to access and the different parts of the string.
$test = explode('###', $string);
echo $test[0]; // outputs: Intro Title
echo $test[1]; // outputs: Some description
and till here it's working fine. But I need to be able to access as well the second part the same way
echo $test[0]; // to output: Intro Title Two
I've tried with a foreach, but it seems to work
foreach ($string as $key) {
$second = explode('\\\', $key);
}
I can't figure out how to do it.
$string ="Intro Title ### Some description ### a link \\\
Intro Title Two ### Description Two ### link 2 \\\
And so ... can be infinite";
$firstExplode = explode('###', $string);
foreach ($firstExplode as $key) {
$secondExplode = explode("\\\\", $key);
var_dump($secondExplode);
}
Note here I use four backslashes instead of just the 3 due to escaping issues.
To answer you question
You can explode on the new-lines first and then in a foreach loop explode on your delimitter. Then you wouldn't even need the back slashes at the end of each line anymore.
<?php
$i = 0;
$lines = explode("\n", $string);
foreach($lines as $line) {
$data[$i] = explode('###', $line);
$i++;
}
To improve your code:
Unless you really depend on this custom file format I would recommend using a standard format like xml, yml or json.
The simplest approach woulr probably be json:
<?php
$string <<<EOT
[
{ "title": "Intro Title", "Description": "Some description", "link": "a link" },
{ "title": "Intro Title 2", "Description": "Some other description", "link": "a second link" }
]
EOT;
$data = json_decode($string, true);
print_r($data);
If it is one string :
$string ="Intro Title ### Some description ### a link \\\
Intro Title Two ### Description Two ### link 2 \\\
And so ... can be infinite";
$string_parts = explode("\\\",$string);
foreach($string_parts as $key=>$val){
$temp = explode('###', $val);
echo $temp[0]; // outputs: Intro Title
echo $temp[1]; // outputs: Some description
}
Related
I have file and I want to replace one word with another like in array. For example I have file.txt and array:
$arr = array(array("milk", "butter"), array("dog", "cat"))
So I want to replace all instances of "milk" with "butter" -- or all instances of "dogs" with "cats" in the text file.
How can I achieve this?
You can try like this;
<?php
// get file content
$text = file_get_contents("file.txt");
$arr = array(array("milk", "butter"), array("dog", "cat"));
foreach($arr as $val){
//replace text with your pattern
$text = str_replace($val[0],$val[1],$text);
}
echo $text;
This code replaces all occurrences of the first word of each inner array with the second word (the correspondent).
$txt = file_get_contents('file.txt'); //text example 'My dog loves milk. My cat loves butter.';
$words = array(array('milk', 'butter'), array('dog', 'cat'));
$result = $txt;
foreach($words as $word){
$result = str_replace($word[0], $word[1], $result);
}
echo 'Before: ' . $txt;
echo '<br>';
echo 'After: ' . $result;
file_put_contents('file2.txt', $result); // won't replace the file so you can see the difference.
Output:
Before: My dog loves milk. My cat loves butter.
After: My cat loves butter. My cat loves butter.
Notes:
This is one way: it doesn't change one by the other. It replaces the first with the second;
It's not checking for malformed;
It must be of same case (case sensitive).
How can I separate each link from my string:
$field = "www.link1.com
www.link2.com";
And output them like this (expected output):
link1 title
www.link1.com
link2 title
www.link2.com
My current code looks like this:
<?php
$field =
"www.link1.com
www.link2.com";
if ($field == "link1");
{
$output="link1 title</br>".$field ;
}
echo $output;
?>
But it only outputs this (current output):
link1 title
www.link1.com www.link2.com
So how can I change/modify my code to get the urls separated and print them like shown above?
This should work for you:
Here I first explode() your string into an array, so that we have each url as array element.
Then we just loop through each link and print them. We also grab the name between www. and the next dot with preg_replace().
$arr = array_map("trim", explode(PHP_EOL, $field));
foreach($arr as $v) {
echo $v . " title<br>";
echo preg_replace("/^www\.([^\.]*)(.*?)$/", "$1", $v) . "<br><br>";
}
I have a problem. I need to get some lines of a page like this:
Text text text ...
Porto-Portugal-May-2013
Barcelona-Spain-April-2013
Text text text text text ...
Madrid-Spain-April-2013
Text text text ...
I need filter so that only appear the following:
Porto-Portugal-May-2013
Barcelona-Spain-April-2013
Madrid-Spain-April-2013
(lines with 3 dashes)
It’s possible with preg_match_all or other function?
I use cURL to get page content.
I have tried:
$body = " Text text text ...
Porto-Portugal-May-2013
Barcelona-Spain-April-2013
Text text text text text ...
Madrid-Spain-April-2013
Text text text ...";
preg_match_all("/^(.*?)-(.*?)-(.*?)-(.*?)\/",$body, $match);
for($i=0;$i<sizeof($match[1]);$i++)
{
echo $match[1][$j].'<br/>';
}
Thank you.
^ means "start of string".
Add the m modifier to make it mean "start of line" instead.
Then it's easier:
preg_match_all("/^(?:[^-\n]+-){3}[^-\n]+$/m",$body,$matches);
var_dump($matches[0]);
This should output an array containing each line that matched.
In the case of defined years in the last of your lines, you don't need regex to complete this task, as follows:
<?php
$yearsList = array(2013, 2014);
$body = " Text text text ...
Porto-Portugal-May-2013
Barcelona-Spain-April-2013
Text text text text text ...
Madrid-Spain-April-2013
Text text text ...";
$arr = explode("\n",$body);
$res = array();
foreach ($arr as $items){
$itemArr = explode('-', $items);
foreach ($itemArr as $item){
if (in_array($item, $yearsList)) $res[] = $items;
}
}
echo "<pre>";
print_r($res);
?>
View This DEMO: http://codepad.org/fdhwEJC4
For instance I have this piece of data:
array(
1 => 'Metallica',
2 => 'Megadeth',
3 => 'Anthrax',
4 => 'Slayer',
5 => 'Black Sabbath',
);
And I have this piece of text:
My first favorite band is: #band{2}, and after that it's: #band1. My
over-all first metal band was: #band{5}, and I sometimes enjoy
headbaning while listening to: #band3 or #band{4}.
So after the RegEx, it should look like this:
My first favorite band is: Megadeth, and after that it's: Metallica.
My over-all first metal band was: Black Sabbath, and I sometimes enjoy
headbaning while listening to: Anthrax or Slayer.
So, I need a pattern/example how can I extract numbers from these two patterns:
#band{NUMERIC-ID} or #bandNUMERIC-ID
No need for regular expressions, just use str_replace():
$map = array();
foreach ($bands as $k => $v){
$map["#band".$k] = $v;
$map["#band{".$k."}"] = $v;
}
$out = str_replace(array_keys($map), $map, $text);
A demo: http://codepad.org/uPqGXGg6
If you want to use regular expressions:
$out = preg_replace_callback('!\#band((\d+)|(\{(\d+)\}))?!', 'replace_band', $text);
function replace_band($m){
$band = $GLOBALS['bands'][$m[2].$m[4]];
return $band ? $band : 'UNKNOWN BAND';
}
A demo: http://codepad.org/2hNEqiCk
[edit] updated for multiple forms of the token to replace
try something like this
$txt = 'your text with bands';
foreach($arr as $key=>$val){
$txt = preg_replace('/#band'.$key.'([^0-9])/', $val.'$1', $txt);
$txt = preg_replace('/#band{'.$key.'}/', $val.'$1', $txt);
}
//detect the error
if(preg_match('/#band[^0-9]+/', $txt) || preg_match('/#band{[^0-9]+}/', $txt){
//error!!!
}
//replace the non found bands with a string
$txt = preg_replace('/#band[^0-9]+/', 'failsafe', $txt);
$txt = preg_replace('/#band{[^0-9]+}/', 'failsafe', $txt);
I have a great little script that will search a file and replace a list of words with their matching replacement word. I have also found a way to prevent preg_replace from replacing those words if they appear in anchor tags, img tags, or really any one tag I specify. I would like to create an OR statement to be able to specify multiple tags. To be clear, I would like to prevent preg_replace from replacing words that not only appear in an anchor tag, but any that appear in an anchor,link,embed,object,img, or span tag. I tried using the '|' OR operator at various places in the code with no success.
<?php
$data = 'somefile.html';
$data = file_get_contents($data);
$search = array ("/(?!(?:[^<]+>|[^>]+<\/a>))\b(red)\b/is","/(?!(?:[^<]+>|[^>]+<\/a>))\b(white)\b/is","/(?!(?:[^<]+>|[^>]+<\/a>))\b(blue)\b/is");
$replace = array ('Apple','Potato','Boysenberry');
echo preg_replace($search, $replace, $data);?>
print $data;
?>
looking at the first search term which basically says to search for "red" but not inside :
"/(?!(?:[^<]+>|[^>]+<\/a>))\b(red)\b/is"
I am trying to figure out how I can somehow add <\/link>,<\/embed>,<\/object>,<\/img> to this search so that preg_replace doesn't replace 'red' in any of those tags either.
Something like this?:
<?php
$file = 'somefile.html';
$data = file_get_contents($file);
print "Before:\n$data\n";
$from_to = array("red"=>"Apple",
"white"=>"Potato",
"blue"=>"Boysenberry");
$tags_to_avoid = array("a", "span", "object", "img", "embed");
$patterns = array();
$replacements = array();
foreach ($from_to as $from=>$to) {
$patterns[] = "/(?!(?:[^<]*>|[^>]+<\/(".implode("|",$tags_to_avoid).")>))\b".preg_quote($f
rom)."\b/is";
$replacements[] = $to;
}
$data = preg_replace($patterns, $replacements, $data);
print "After:\n$data\n";
?>
Result:
Before:
red
<span class="blue">red</span>
blue<div class="blue">white</div>
<div class="blue">red</div>
After:
red
<span class="blue">red</span>
Boysenberry<div class="blue">Potato</div>
<div class="blue">Apple</div>