diff --git a/README.md b/README.md index 9380833..c10ff10 100644 --- a/README.md +++ b/README.md @@ -106,6 +106,7 @@ DomQuery::create('')->attr('title') // hello - `.wrap( [content] )` - `.wrapAll( [content] )` - `.wrapInner( [content] )` +- `.unwrap( )` - `.remove( [selector] )` \* __[content]__ can be html or an instance of DomQuery|DOMNodeList|DOMNode diff --git a/src/Rct567/DomQuery/DomQuery.php b/src/Rct567/DomQuery/DomQuery.php index d48db60..ba880ba 100644 --- a/src/Rct567/DomQuery/DomQuery.php +++ b/src/Rct567/DomQuery/DomQuery.php @@ -958,7 +958,9 @@ private function importNodes($content, callable $import_function) foreach ($this->nodes as $node) { foreach ($content->getNodes() as $content_node) { if ($content_node->ownerDocument === $node->ownerDocument) { - $imported_node = $content_node->cloneNode(true); + // No clone so that the element used with replaceWith() + // gives a connected dom element. + $imported_node = $content_node; } else { $imported_node = $this->document->importNode($content_node, true); } @@ -1113,12 +1115,6 @@ public function replaceWith() $node->parentNode->removeChild($node); }); - foreach (\func_get_args() as $new_content) { - if (!\is_string($new_content)) { - self::create($new_content)->remove(); - } - } - return $removed_nodes; } @@ -1202,6 +1198,21 @@ public function wrapInner() return $this; } + /** + * Unwrap all the the matched elements. + * + * @param string|self|callable|\DOMNodeList|\DOMNode|false|null $selector expression that filters the set of matched elements + * + * @return self + */ + public function unwrap($selector=null) + { + foreach ($this->parent($selector) as $parent) { + $parent->replaceWith($this->nodes); + } + return $this; + } + /** * Check if property exist for this instance * diff --git a/tests/Rct567/DomQuery/Tests/DomQueryManipulationTest.php b/tests/Rct567/DomQuery/Tests/DomQueryManipulationTest.php index 74ad91f..7b8d0a2 100644 --- a/tests/Rct567/DomQuery/Tests/DomQueryManipulationTest.php +++ b/tests/Rct567/DomQuery/Tests/DomQueryManipulationTest.php @@ -105,6 +105,36 @@ public function testWrapWithMultipleElementsWrapper() $this->assertEquals("

Hello

", (string) $dom); } + /* + * Test unwrap. + */ + public function testUnwrap() + { + $expected = 'this is a test'; + $doc = DomQuery::create('
this is a test
'); + $doc->find('article > a')->first()->unwrap(); + $this->assertEquals($expected, (string) $dom); + } + + /* + * Test wraping and unwrapping. + */ + public function testWrapAllandUnwrap() + { + $input = '
' . PHP_EOL . + '
' . PHP_EOL . + '
' . PHP_EOL . + ' ' . PHP_EOL . + '
' . PHP_EOL . + '
' . PHP_EOL . + ' ' . PHP_EOL . + '
' . PHP_EOL . + '
' . PHP_EOL . + '
'; + $dom->find('#target')->wrapAll('
')->parent()->children()->unwrap(); + $this->assertEquals($input, (string) $dom); + } + /* * Test remove */